标签:catch com str res rip ams lis html state
Android 开发上常用的json解析方式有:Gson, fastJson,jackson。
因为jackjson jar包会比较大点(700+k),Gson和fastjson的功能又基本够用,所以一直没正式用过jackjson。自己有用的就是Gson和fastjson
//解成对象
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)
//解析成对象
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)
可维护性 > 正确性 > 性能
说点实在的,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, String.class);
Log.d("test", "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, String.class);
Log.d("test", "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 $
from: http://www.voidcn.com/blog/lckj686/article/p-6000736.html
Gson 与 fastJson 在使用上的差异(fastJson的优点)
标签:catch com str res rip ams lis html state
原文地址:http://www.cnblogs.com/GarfieldEr007/p/6822295.html