--- Gson java object representation of an object that implements Json

Gson

Previous blog talked about the serialization of java, jdk own serialization has the following advantages and disadvantages:

1, java serialization methods are used jdk own, you do not need to introduce a third party to use jar package.

2, the sequence of the generated java byte array can not be used across platforms, data can only be used after serialization deserialize java language, using narrow.

3, java comes serialization data generated by occupying more space, while the serialization and deserialization efficiency is very low.

  So in fact, we consider the sequence of simply trying to convert objects into IO data can be identified, so the object can be converted into data format json or xml format for transmission or storage, this blog we will introduce the common json of the way, java commonly used json libraries have: Gson, Fastjson, Jackson, author of json library is actually used fastjson, but due to the recent burst fastjson relatively large loophole, at the same time upgrade also want to learn about other json of the way, so this tell us about the basic use of Gson.

 

Gson basic use

  Providing the toJson Gson () and fromJson () are two ways to provide serialization and deserialization process, while providing a variety of method overloading.

  First, the definition of a Person class, for later use demo:

 

public class Person {
    private String name;
    private int age;
    private String sex;

    public Person(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "姓名为:"+name+"年龄为:"+age+"性别为:"+sex;
    }
}

 

  Write a simple program that uses serialization and de-serialization:

public  class GsonDemo {
     public  static  void main (String [] args) { 
        Gson GSON = new new Gson ();
         // define a class Person 
        Person Person = new new Person ( "Joe Smith", 18, "M" );
         // sequence of 
        String GsonObject = gson.toJson (Person);
         // output: { "name": "Joe Smith", "age": 18, "sex": " M"} 
        System.out.println (GsonObject);
         / / deserialization 
        Person person1 = gson.fromJson ( "{\ " name \ ": \" John Doe \ ", \" age \ " : 18, \" sex \ ": \" M \ "}", Person.class);
        //Output: Name as: Joe Smith age: 18 gender: Male 
        System.out.println (PERSON1); 
    } 
}

 

Gson use aliases

  Gson using aliases way mainly achieved through @SerializedName annotations, in two ways:

    @SerializedName("person_name")
    private String name;
    @SerializedName(value = "person_age",alternate = {"age","ages"})
    private int age;

  When using the annotation and there is only a single value, the serialization and de-serialization uses the value assigned in the notes, and use alternate, it will only use the name person_age in the sequence of the time and in time will deserialization identifying person_age, age, ages value of three kinds of names, has been serialized data will only appear in the alias identification rearmost performed procedure is as follows:

public  class GsonDemo {
     public  static  void main (String [] args) { 
        Gson GSON = new new Gson ();
         // define a class Person 
        Person Person = new new Person ( "Joe Smith", 18, "M" );
         // sequence of 
        String GsonObject = gson.toJson (Person);
         // output: { "person_name": "Joe Smith", "person_age": 18, "sex": " M"} 
        System.out.println (GsonObject);
         / / deserialization occurs only identify rearmost age: 17 years 
        Person person1 = gson.fromJson ( "{\ " person_name \ ": \" John Doe \ ", \" ages \ " : 18, \"person_age\":16,\"age\":17,\"sex\":\"男\"}",Person.class);
         // output: Name as: Joe Smith age: 17 gender: Male 
        System.out.println (PERSON1); 
    } 
}

 

Gson processing properties NULL

  When using Gson serialization, if a property is null then the contents of the property contains a sequence of not, this is probably not the result we want, although after a property is empty, but we still have to serialize it will show up, a sequence of the following field is empty:

public  class GsonDemo {
     public  static  void main (String [] args) { 
        Gson GSON = new new Gson ();
         // define a class Person 
        Person Person = new new Person ( "Joe Smith", 18 is, null );
         // serialization 
        String = GsonObject gson.toJson (Person);
         // output: {{ "person_name": "Joe Smith", "person_age": 18 is} 
        System.out.println (GsonObject); 
    } 
}

  A tool GsonBuilder processing sequence of objects with a null question Gson while the sequence may further fixed time format attribute:

public  class GsonDemo {
     public  static  void main (String [] args) { 
        Gson GSON = new new Gson ();
         // define a class Person 
        Person Person = new new Person ( "Joe Smith", 18 is, null );
         // serialization, setDateFormat () just to show only a fixed date format 
        String = GsonObject new new GsonBuilder () serializeNulls () setDateFormat ( "YYYY / the MM / DD.". ) .create () the toJson (Person);.
         // output: { "person_name ":" Joe Smith "," person_age ": 18 is," Sex ": null} 
        System.out.println (GsonObject);
         // deserialization, only recognize the presence rearmost age: 17 years
        = PERSON1 the Person new new .... GsonBuilder () serializeNulls () setDateFormat ( "YYYY / the MM / DD") Create () fromJson ( "{\" PERSON_NAME \ ": \" John Doe \ ", \" person_age \ " : 18, \ "sex \": null} ", the Person. class );
         // output: name as: Joe Smith age: 18 gender: null 
        System.out.println (PERSON1); 
    } 
}

 

Gson deal with generics

  If the Gson For Number, boolean, Object, String, Array can be used directly in the following manner to

 

public class GsonDemo {
    public static void main(String[] args) {
        Gson gson=new Gson();
        String StringObject="[\"Android\",\"Java\",\"PHP\"]";
        String[] strings=gson.fromJson(StringObject,String[].class);
     /* 输出如下:
        Android
        ava
        PHP*/
        for (String s:strings){
            System.out.println(s);
        }
    }
}

 

  To use List <String> .class versa, so Gson provides new TypeToken <List <String >> () {}. GetType () is provided by way of supporting generic sequence, and this way also the generic web often return a response to a scene, such as a request to return the rear end side of the web {code: "0", message: "success", data {...}}.

public class RespData<T> {
    public int code;
    public String message;
    public T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

Returns a result based on the definition, as a result of the rear end may return a variety of different situations, it is used to indicate a generic data type returned by the backend, the result data is provided to return a String can be a simple

public class RespDataObj {
    public String data;

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }
}

Deserialize follows:

public class GsonDemo {
    public static void main(String[] args) {
        Gson gson=new Gson();
        String StringObject="{\"code\":\"0\",\"message\":\"success\",\"data\":{\"data\": \"hello java\"}}";

        RespData<RespDataObj> res=gson.fromJson(StringObject,new TypeToken<RespData<RespDataObj>>(){}.getType());
        //输出结果
        System.out.println(res.getData().getData());
    }
}

 

Guess you like

Origin www.cnblogs.com/rhodesis/p/11531267.html