zoukankan      html  css  js  c++  java
  • Google Gson用法

    Google Gson用法

    the latest version is 2.8.0. If you're using Gradle, add the following line:

    compile 'com.google.code.gson:gson:2.8.0'  
    

    If you're using Maven, you can add the following dependency:

    <dependencies>  
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
            <scope>compile</scope>
        </dependency>
    </dependencie>

    Primitives Examples

    // Serialization
    Gson gson = new Gson();
    gson.toJson(1);            // ==> 1
    gson.toJson("abcd");       // ==> "abcd"
    gson.toJson(new Long(10)); // ==> 10
    int[] values = { 1 };
    gson.toJson(values);       // ==> [1]
    
    // Deserialization
    int one = gson.fromJson("1", int.class);
    Integer one = gson.fromJson("1", Integer.class);
    Long one = gson.fromJson("1", Long.class);
    Boolean false = gson.fromJson("false", Boolean.class);
    String str = gson.fromJson(""abc"", String.class);
    String[] anotherStr = gson.fromJson("["abc"]", String[].class);

    Object Examples

    class BagOfPrimitives {
      private int value1 = 1;
      private String value2 = "abc";
      private transient int value3 = 3;
      BagOfPrimitives() {
        // no-args constructor
      }
    }
    
    // Serialization
    BagOfPrimitives obj = new BagOfPrimitives();
    Gson gson = new Gson();
    String json = gson.toJson(obj);  
    
    // ==> json is {"value1":1,"value2":"abc"}

    Note that you can not serialize objects with circular references since that will result in infinite recursion.

    // Deserialization
    BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);
    // ==> obj2 is just like obj

    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:

    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.

    Gson can not deserialize {"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.

    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.

    Array Examples

    Gson gson = new Gson();
    int[] ints = {1, 2, 3, 4, 5};
    String[] strings = {"abc", "def", "ghi"};
    
    // Serialization
    gson.toJson(ints);     // ==> [1,2,3,4,5]
    gson.toJson(strings);  // ==> ["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.

    Collections Examples

    Gson gson = new Gson();
    Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);
    
    // Serialization
    String json = gson.toJson(ints);  // ==> json is [1,2,3,4,5]
    
    // Deserialization
    Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
    Collection<Integer> ints2 = gson.fromJson(json, collectionType);
    // ==> ints2 is same as ints

    gson/UserGuide.md at master · google/gson
    https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-Users

    Gson — Getting Started with Java-JSON Serialization & Deserialization
    https://futurestud.io/tutorials/gson-getting-started-with-java-json-serialization-deserialization

    google/gson: A Java serialization/deserialization library that can convert Java Objects into JSON and back.
    https://github.com/google/gson


    FasterXML Jackson学习笔记

  • 相关阅读:
    针对数据库开发人员的性能调优小提示
    Oracle EBS 12 目录结构
    程序集反射
    DataTable.Select() 返回DataTable结果
    有趣的23中设计模式
    『原创』用C++开发WM应用系列(5)——接触ListBox控件
    『原创』用C++开发WM应用系列(1)——"Hello World" Pro!(上)
    【参考】在PPC上面检查文件MD5
    用C++开发WM应用系列文章索引
    『原创』用C++开发WM应用系列(1)——"Hello World" Pro!(下)
  • 原文地址:https://www.cnblogs.com/it-tsz/p/11749669.html
Copyright © 2011-2022 走看看