首页 > 系统 > Android > 正文

Android解析Json三种方式

2019-11-08 03:02:26
字体:
来源:转载
供稿:网友

               后台返回的数据可能是xml或是Json。昨天研究了解析XML,今天来试试Json.在现在Json用的比以前要普遍。

不管是从界面上的用户体验感还是在资源消耗上,Json都有了较大的优势。今天试试三种方式解析

               一.原生态解析Json,代码如下:

                

   
URL url=new URL(getString(R.string.server_name)+"person.json");HttpURLConnection connection= (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");connection.setConnectTimeout(5000);int code=connection.getResponseCode();if (code==200){    InputStream is=connection.getInputStream();    BufferedReader br=new BufferedReader(new InputStreamReader(is));    String str=null;    StringBuffer stringBuffer=new StringBuffer();    while((str=br.readLine())!=null){        stringBuffer.append(str);    }
//原生态解析json//                    JSONObject jsonObject=new JSONObject(stringBuffer.toString());//                    int list=jsonObject.getInt("list");//                    Log.i("test","长度:"+list);//                    JSONArray jsonArray=jsonObject.getJSONArray("persons");//                    for (int i = 0; i < jsonArray.length(); i++) {//                        JSONObject object=jsonArray.getJSONObject(i);//                        int pid=object.getInt("pid");//                        String pname=object.getString("pname");//                        int page=object.getInt("page");//                        Log.i("test",pid+"  "+page+" "+pname);//                    }

至于其他配置网络环境,获取Json文件数据参看昨天博客代码。

                     二.    Gson解析Json.这个需要添加jar包,右击项目,然后如图

          

联网下载,也可自己手动导入jar包,接下来写代码。须得创立两个尸体类。一个装其中的大对象,另一个装其中一个对象中的各小对象,注意的json文件中的每一个对象名一致

               //Gson解析Json//                    Gson gson=new Gson();//                    BigPerson bigPerson=gson.fromJson(stringBuffer.toString(),BigPerson.class);//                    Log.i("test",bigPerson.getList()+"");////                    List<SmallPerson> persons=bigPerson.getPersons();//                    for (SmallPerson person:persons){//                        Log.i("test",person.toString());//                    }

                三.Fast解析Json,也要用到实体类

//Fast解析JsonBigPerson bigPerson=JSON.parSEObject(stringBuffer.toString(),BigPerson.class);Log.i("test",bigPerson.getList()+"");List<SmallPerson> persons=bigPerson.getPersons();for (SmallPerson person:persons){    Log.i("test",person.toString());}

   原生态做法更接近了解底层,Gson和Fast都有其自身封装好的方法只等我们去调用。相对来说后两种比较容易但我们都应该多练习,各有优点。

       

              


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表