Retrofit+fastjson

来源:互联网 发布:狼牙军品专卖店一淘宝 编辑:程序博客网 时间:2024/05/21 05:38

Android中广泛应用json解析的三方库有两种:

1 Google的Gson(几乎解决所有问题)2 阿里巴巴的fastjson(几乎解决所有问题,数据量很大的时候比gson快)

看到了快的优点和阿里产品,我想大家有必要学习一下

fastjson github地址

目前最新的版本是:1.2.37

1 项目中如何使用?

使用起来很简单,就记住两个最常用的方法即可

 Model model = new Model(); String json = JSON.toJSONString(model);//对象转json字符串 Model model2 = JSON.parseObject(json, Model.class);//字符串转json
源码的第一句也是表达这个意思:This is the main class for using Fastjson. You usually call these two methods {@link #toJSONString(Object)} and {@link #parseObject(String, Class)}.

2 Retrofit项目中如何使用?

现在的App项目都是Retrofit+Rxjava+OKhttp,默认一般也是Gson解析,如何改成fastjson呢?

主要是利用Retrofit可以灵活自定义转换工厂的优点,将fastjson包装成工厂,见下面的这个三方库

retrofit-converter-fastjson github地址

打开这个github地址,目前最新的版本是

compile 'org.ligboy.retrofit2:converter-fastjson-android:2.1.0'
 Retrofit retrofit = new Retrofit.Builder()  .baseUrl("https://api.example.com")  .addConverterFactory(FastJsonConverterFactory.create())//重点是这句话  .build();