一、android 常用的json解析方式
Android 开发上常用的json解析方式有:Gson, fastJson,jackson。
因为jackjson jar包会比较大点(700+k),Gson和fastjson的功能又基本够用,所以一直没正式用过jackjson。自己有用的就是Gson和fastjson
二、基本使用方式
@H_502_8@Gson//解成对象
Fromat mFromat = new Gson().fromJson(jsonStringObject,Fromat.class);
//解成对象组
LinkedList<Fromat> list = new LinkedList<MainActivity.Fromat>();
Type type = new TypeToken<LinkedList<Fromat>>(){}.getType();
list = new Gson().fromJson(jsonStringArray,type);
//泛型统一封装时 需要传个 type 进来
new TypeToken<LinkedList<Fromat>>(){}.getType();
fromJson(String json,Type typeOfT)
public <T> T fromJson(String json,Type typeOfT)
fastJson
//解析成对象
Fromat fastjsonObject = JSON.parSEObject(jsonObjectString,Fromat.class);
//解析成对象组
List<Fromat> fastjsonArray = JSON.parseArray(jsonArrayString,Fromat.class);
//泛型统一封装时 需要传个 type 进来 或者TypeReference 也可以也是调用的type
new TypeReference<Fromat>() {}
new TypeReference<Fromat>() {}.getType()
public static <T> T parSEObject(String input,Type clazz,Feature... features)
public static <T> T parSEObject(String text,TypeReference<T> type,Feature... features)
三、fastjson 的优点
可维护性 > 正确性 > 性能
说点实在的,Gson在遇到 {} [] 这种json关键字的时候直接解析为string 报错。fastjson是可以解析
demo代码:
String jsonObjectString = "{\"status\": 0}";
String jsonArrayString = "[{\"status\": 0}]";
//fastJson
String fastjsonObject = JSON.parSEObject(jsonObjectString,String.class);
Log.d("test","fastJson string {} = " + fastjsonObject);
String fastjsonArray = JSON.parSEObject(jsonArrayString,"fastJson string [] = " + fastjsonArray);
//Gson
try {
String gsonObject = new Gson().fromJson(jsonObjectString,String.class);
Log.d("test","gson string {} = " + gsonObject);
}catch (Exception e){
Log.d("test","gson string {} = " + e);
}
try {
String gsonArray = new Gson().fromJson(jsonArrayString,"gson string {} = " + gsonArray);
}catch (Exception e){
Log.d("test","gson string [] = " + e);
}
结果: D/test: fastJson string {} = {“status”:0} D/test: fastJson string [] = [{“status”:0}] D/test: gson string {} = com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: D/test: gson string [] = com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 2 path $