温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

用Gson解析json文件

发布时间:2020-07-07 09:42:05 来源:网络 阅读:4574 作者:liushaodong 栏目:开发技术

一般解析json方法自己写起来较为繁琐,利用开源的API可以节省很多事,达到快速的开发。


1) 自己写的代码:

   例如:

   private void parserJSON(String strJSON)

       {

           try

           {

               JSONArray jsonArray = new JSONArray(strJSON);

               for (int j = 0; j < jsonArray.length(); j++)

               {

                   JSONObject jsonObject = jsonArray.getJSONObject(j);

                   String icon1Url = jsonObject.getString("icon1Url");

                   String fristTile = jsonObject.getString("fristTitle");

                   String title = jsonObject.getString("title");

                   String message = jsonObject.getString("message");

                   String p_w_picpathUrl = jsonObject.getString("p_w_picpathUrl");

                   String time = jsonObject.getString("time");

                   String from = jsonObject.getString("from");

                   mList.add(new HomeData(icon1Url, fristTile, title, message, p_w_picpathUrl,                                                         time, from));

               }

   

           }

           catch (JSONException e)

           {

               e.printStackTrace();

           }

   

       }


如果json的数据多起来,就要写很多的get,就比较烦了


2) 用gson解析:

   例如:


   private void parserJSON(String strJSON)

   {

       Gson gson = new Gson();

       Type type = new TypeToken<List<HomeData>>()

                       {

                       }.getType();

       List<HomeData> mDataInfo = gson.fromJson(strJSON, type);

   }

   

总结: 两者用起来存数据的类HomeData,容器List这多少不了,用了Gson就是不用自己写get语句

       不用写try catch,方便了很多。


Gson用法:

   1. 首先,从 code.google.com/p/google-gson/downloads/list下载GsonAPI:

google-gson-2.2.4-release.zip

   2.  把gson-2.2.4.jar copy到libs(项目res目录新建一个libs文件夹)中。

       

   3. 代码中使用:就是上面的 2) 的写法,这是解析一个jsonArray,类的属性要跟json文件中的            key,完全一致,属性的类型是value的类型




向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI