解析json

来源:互联网 发布:sql server 教程 高级 编辑:程序博客网 时间:2024/06/08 03:18

解析json我知道三种方案:
1.org.json
原版
数据量极小的数据解析速度快
2.Gson
谷歌推出
数据量中等的数据解析速度快
3.fastjson
阿里推出
数据量大的数据解析速度快
数据量大小,我是按照5000条左右划分的。

原版的就不做讲解了,说一下使用fastjson和Gson。
采用Android Studio开发工具。

贴一段json:

{code: 200,item: [{id: "79734",type: 1,image: "http://www.reginer.xyz/images/img_1.jpg",name: "道具1",price: "登录看价",promotion_price: "99999.00"},{id: "79724",type: 2,description: "这个可以有",name: "描述1",price: "登录看价",promotion_price: "830.00"},{id: "79724",type: 1,image: "http://www.reginer.xyz/images/img_2.jpg",name: "道具2",price: "登录看价",promotion_price: "830.00"}]}

两个框架都来解析这段json。

1.添加两个依赖:

compile 'com.google.code.gson:gson:2.8.0'compile 'com.alibaba:fastjson:1.2.23'

2.创建各自的实体类,这里我使用gsonformat插件自动创建了,类就不贴了。

3.读取assets下的文件的json数据:

private String getFromAssets(String fileName) {        try {            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));            BufferedReader bufReader = new BufferedReader(inputReader);            String line;            String Result = "";            while ((line = bufReader.readLine()) != null)                Result += line;            return Result;        } catch (Exception e) {            e.printStackTrace();        }        return null;    }

还有一点代码:

private String source;source = getFromAssets("date");

4–1:Gson解析:

private void analyticalJsonByGson() {        GsonAnalytical mGsonContent = new Gson().fromJson(source, GsonAnalytical.class);        Log.d(TAG, "analyticalJsonByGson: " + mGsonContent.getCode());        for (int i = 0; i < mGsonContent.getItem().size(); i++) {            Log.d(TAG, "Description: " + mGsonContent.getItem().get(i).getDescription() +                    "image  is:::" + mGsonContent.getItem().get(i).getImage() + "Promotion_price is::"                    + mGsonContent.getItem().get(i).getPromotion_price());        }    }

4–2:fastjson解析:

private void analyticalJsonByFastJson() {        FastJsonAnalytical mFastJsonAnalytical = JSON.parseObject(source, FastJsonAnalytical.class);        Log.d(TAG, "mFastJsonAnalytical: " + mFastJsonAnalytical.getCode());        for (int i = 0; i < mFastJsonAnalytical.getItem().size(); i++) {            Log.d(TAG, "Description: " + mFastJsonAnalytical.getItem().get(i).getDescription() +                    "image  is:::" + mFastJsonAnalytical.getItem().get(i).getImage() + "Promotion_price is::"                    + mFastJsonAnalytical.getItem().get(i).getPromotion_price());        }    }

两种方式几乎一毛一样。

0 0
原创粉丝点击