日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

google Gson學(xué)習(xí)筆記及與json-lib的比較

 hehffyy 2011-01-11
因?yàn)間son網(wǎng)上的幫助文檔打開時(shí)比較慢,所以把幫助文檔摘錄如此,方便查看:
1. 基本類型轉(zhuǎn)化
Java代碼 
public static void main(String[] args) {  
        Gson gson = new Gson();  
        System.out.println(gson.toJson(1)); // ==> prints 1  
        System.out.println(gson.toJson("abcd"));// ==> prints "abcd"  
        System.out.println(gson.toJson(new Long(10)));// ==> prints 10  
        int[] values = { 1 };  
        System.out.println(gson.toJson(values));// ==> prints [1]  
        System.out.println("============");  
  
        int one = gson.fromJson("1", int.class);  
        Integer one1 = gson.fromJson("1", Integer.class);  
        Long one2 = gson.fromJson("1", Long.class);  
        String str = gson.fromJson("\"abc\"", String.class);  
        String anotherStr = gson.fromJson("[\"abc\"]", String.class);  
        int[] ints = gson.fromJson("[1,2,3,4,5]", int[].class);  
        Boolean b = gson.fromJson("false", Boolean.class);  
        System.out.println(b == false); //==> prints true  
    }  
 2.對(duì)象轉(zhuǎn)化
Java代碼 
public class BagOfPrimitives {  
  
    private int           value1    = 1;  
    private String        value2    = "abc";  
//是用于聲明變量在序列化的時(shí)候不被存儲(chǔ)  
    private transient int   value3  = 3;  
  
    BagOfPrimitives() {  
        // no-args constructor  
    }  
  
    public static void main(String[] args) {  
        BagOfPrimitives obj = new BagOfPrimitives();  
        Gson gson = new Gson();  
        String json = gson.toJson(obj);    
        System.out.println(json); //==> json is {"value1":1,"value2":"abc"}  
          
        BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   
        System.out.println(obj2.value1);  
        System.out.println(obj2.value2);  
        System.out.println(obj2.value3);//==>3  
          
        String json1 = "{'value1':1,'value2':'abc','value3':4}";  
        BagOfPrimitives obj3 = gson.fromJson(json1, BagOfPrimitives.class);   
        System.out.println(obj3.value1);  
        System.out.println(obj3.value2);  
        System.out.println(obj3.value3); //==>3  
    }  
}  
Note that you can not serialize objects with circular references since that will result in infinite recursion. 
如果要是用json lib的話,上面的代碼可以寫成如下所示:
Java代碼 
String json1 = "{'value1':1,'value2':'abc','value3':4}";  
JSONObject jsonObj = JSONObject.fromObject( json1 );   
BagOfPrimitives obj3 = (BagOfPrimitives) JSONObject.toBean( jsonObj, BagOfPrimitives.class );  
 Finer Points with Objects
It is perfectly fine (and recommended) to use private fields 
There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default. 
If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
This implementation handles nulls correctly
While serialization, a null field is skipped from the output
While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null
If a field is synthetic , it is ignored and not included in JSON serialization or deserialization
Fields corresponding to the outer classes in  inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization
Nested Classes (including Inner Classes)
Gson can serialize static nested classes quite easily. 

Gson can also deserialize static nested classes. However, Gson can not automatically deserialize the pure inner classes since their no-args constructor also need a reference to the containing Object which is not available at the time of deserialization. You can address this problem by either making the inner class static or by providing a custom InstanceCreator for it. Here is an example: 
Java代碼 
public class A {  
  public String a;  
  
  class B {  
  
    public String b;  
  
    public B() {  
      // No args constructor for B  
    }  
  }  
}  
 NOTE : The above class B can not (by default) be serialized with Gson.
G s o n   c a n   n o t   d e serialize {"b":"abc"} into an instance of B since the class B is an inner class. if it was defined as static class B then Gson would have been able to deserialize the string. Another solution is to write a custom instance creator for B.
Java代碼 
public class InstanceCreatorForB implements InstanceCreator<A.B> {  
  private final A a;  
  public InstanceCreatorForB(A a)  {  
    this.a = a;  
  }  
  public A.B createInstance(Type type) {  
    return a.new B();  
  }  
}  
The above is possible, but not recommended.
 
數(shù)組例子:
Java代碼 
Gson gson = new Gson();  
int[] ints = {1, 2, 3, 4, 5};  
String[] strings = {"abc", "def", "ghi"};  
  
(Serialization)  
gson.toJson(ints);     ==> prints [1,2,3,4,5]  
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]  
  
(Deserialization)  
int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);  
==> ints2 will be same as ints  
 We also support multi-dimensional arrays, with arbitrarily complex element types
綜合實(shí)例1:
Java代碼 
public class ExampleBean {  
    private String  name;  
    private String  id;  
    private int    age;  
    private boolean isOk;  
      
    public ExampleBean(String name, String id, int age, boolean isOk) {  
        super();  
        this.name = name;  
        this.id = id;  
        this.age = age;  
        this.isOk = isOk;  
    }  
  
    public ExampleBean() {  
    }  
//setter和getter方法  
}  
 測(cè)試:
Java代碼 
public static void main(String[] args) {  
        Gson gson = new Gson();  
        List<ExampleBean> list = new ArrayList<ExampleBean>();  
        for (int i = 0; i < 5; i++) {  
            String name = "xxlong" + i;  
            int age = 20 + i;  
            ExampleBean bean = new ExampleBean(name, i + "", age);  
            list.add(bean);  
        }  
        Type listType = new TypeToken<List<ExampleBean>>() {  
        }.getType();  
        //將list轉(zhuǎn)化成json字符串  
        String json = gson.toJson(list);  
        System.out.println(json);  
        //將json字符串還原成list  
        List<ExampleBean> list2 = gson.fromJson(json, listType);  
    }  
 輸出如下:[{"name":"xxlong0","id":"0","age":20,"isOk":false},{"name":"xxlong1","id":"1","age":21,"isOk":false},{"name":"xxlong2","id":"2","age":22,"isOk":false},{"name":"xxlong3","id":"3","age":23,"isOk":false},{"name":"xxlong4","id":"4","age":24,"isOk":false}]
 
綜合實(shí)例2:
需求:想將字符串{'tableName' :'ys_index_y','year': '2008','params':'[z_expense,z_expense_profit,z_main_margin]','isOperAll':'false','copyToYear':''}還原成對(duì)象OpeerConditions,OpeerConditions對(duì)象代碼如下所示:
Java代碼 
public class OperConditions {  
  
    private String   tableName;  
    private String   year;  
    private String[]    params;  
    private boolean  isOperALl;  
    private String   copyToYear;  
  
    public OperConditions() {  
    }  
  
    public OperConditions(String tableName, String year, String[] params,  
                    boolean isOperALl, String copyToYear) {  
        super();  
        this.tableName = tableName;  
        this.year = year;  
        this.params = params;  
        this.setOperALl(isOperALl);  
        this.copyToYear = copyToYear;  
    }  
//getter和setter方法  
}  
 因?yàn)镺perConditions中有屬性params,它是一個(gè)數(shù)組,所以無(wú)論是用json lib還是gson都不能直接將上面的字符串還原成OperCondtions對(duì)象,可以直接將params分離出來(lái),單獨(dú)處理,我這里選用此種方法來(lái)處理:
json-lib代碼如下:
Java代碼 
public static void main(String[] args) {  
          
        String json = "{'tableName' :'ys_index_y','year': '2008','isOperAll':'false','copyToYear':''}";  
        JSONObject jsonObj = JSONObject.fromObject( json );   
        OperConditions conditions = (OperConditions) JSONObject.toBean( jsonObj, OperConditions.class );  
        System.out.println(conditions.isOperALl() == false); //==>輸出為true  
          
        String json1 = "['z_expense','z_expense_profit','z_main_margin']";  
        JSONArray jsonArray = JSONArray.fromObject(json1);  
        //List<String> list = jsonArray.toList(jsonArray); //這個(gè)方法也可以  
        List<String> list = jsonArray.toList(jsonArray,String.class);  
        conditions.setParams(list.toArray(new String[0]));  
        System.out.println(conditions.getParams()[0]); //==>輸出為z_expense  
    }  
 因?yàn)镴SONArray的toArray()方法返回的是一個(gè)Object[]數(shù)組,所以先將它轉(zhuǎn)化成list,再轉(zhuǎn)化到String數(shù)組。
當(dāng)然由JSONArray轉(zhuǎn)化成list時(shí)也可以使用subList方法,如下所示:
Java代碼 
List<String> list = jsonArray.subList(0, jsonArray.size());  
 或者可以直接使用JSONArray的iterator() 方法迭代它本身直接得到需要的String數(shù)組。
 
如果使用Gson來(lái)完成這一需求,個(gè)人感覺更簡(jiǎn)單,代碼如下所示:
Java代碼 
public static void main(String[] args) {  
  
        String json = "{'tableName' :'ys_index_y','year': '2008','isOperAll':'false','copyToYear':''}";  
        Gson gson = new Gson();  
        OperConditions conditions = gson.fromJson(json, OperConditions.class);  
        System.out.println(conditions.isOperALl() == false); // ==>輸出為true  
  
        String json1 = "['z_expense','z_expense_profit','z_main_margin']";  
        String[] params = gson.fromJson(json1,String[].class);  
        conditions.setParams(params);  
        System.out.println(conditions.getParams()[0]); // ==>輸出為z_expense  
    }  
 Gson可以直接轉(zhuǎn)化成String[]數(shù)組,同時(shí)轉(zhuǎn)化OperConditions時(shí)也比json-lib簡(jiǎn)單。
還有一點(diǎn)是非常值得注意的,就是你的bean中有boolean屬性值時(shí),強(qiáng)烈建議你別像我這個(gè)例子中一樣命名為以is開頭的屬性名,這可能給你帶來(lái)意想不到的錯(cuò)誤,關(guān)于這一點(diǎn)的詳細(xì)解說(shuō)請(qǐng)參看我的文章json lib 學(xué)習(xí)筆記

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多