解析json

解析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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值