Gson 与 fastJson 在使用上的差异(fastJson的优点)
一、android 常用的json解析方式Android 开发上常用的json解析方式有:Gson, fastJson,jackson。 二、基本使用方式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 的优点可维护性 > 正确性 > 性能 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 $ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |