Gson 与 fastJson 在使用上的差异(fastJson的优点)

一、android 常用的json解析方式

Android 开发上常用的json解析方式有:Gson, fastJson,jackson。
因为jackjson jar包会比较大点(700+k),Gson和fastjson的功能又基本够用,所以一直没正式用过jackjson。自己有用的就是Gson和fastjson

二、基本使用方式

Gson

    //解成对象
    Fromat mFromat = new Gson().fromJson(jsonStringObject, Fromat.class);

    //解成对象组
    LinkedList list = new LinkedList();
    Type type = new TypeToken>(){}.getType();
    list = new Gson().fromJson(jsonStringArray, type);

    //泛型统一封装时 需要传个 type 进来
    new TypeToken>(){}.getType();
    fromJson(String json, Type typeOfT)
    public  T fromJson(String json, Type typeOfT) 

fastJson

    //解析成对象
    Fromat fastjsonObject = JSON.parseObject(jsonObjectString, Fromat.class);

    //解析成对象组
    List fastjsonArray = JSON.parseArray(jsonArrayString, Fromat.class);

    //泛型统一封装时 需要传个 type 进来 或者TypeReference 也可以也是调用的type
    new TypeReference() {}
    new TypeReference() {}.getType()
    public static  T parseObject(String input, Type clazz, Feature... features)
    public static  T parseObject(String text, TypeReference 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, 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 $

你可能感兴趣的:(android)