Use the Gson library to translate Java objects into advanced instances of JSON objects _java

Source: Internet
Author: User
Tags tojson

Common conversion operations on structures such as lists and maps can basically satisfy most of the requirements we handle, but sometimes there are special formatting requirements for JSON in the project. For example, the following JSON string parsing:

[{"tableName":"students","tableData":[{"id":1,"name":"李坤","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":2,"name":"曹贵生","birthDay":"Jun 22, 2012 9:54:49 PM"},{"id":3,"name":"柳波","birthDay":"Jun 22, 2012 9:54:49 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]

After analysis, we found that the normal way is not good to handle the above JSON string. Please see how this article is handled:

Entity classes:

Import Java.util.Date; 
  public class Student {private int id; 
  private String name; 
 
  Private Date birthday; 
  public int getId () {return id; 
  The public void setId (int id) {this.id = ID; 
  Public String GetName () {return name; 
  public void SetName (String name) {this.name = name; 
  Public Date Getbirthday () {return birthday; 
  The public void Setbirthday (Date birthday) {this.birthday = birthday; 
        @Override public String toString () {return "Student [birthday= + birthday +", id= "+ ID +", name= " 
  + name + "]"; 
 
  } public class Teacher {private int id; 
 
  private String name; 
 
  Private String title; 
  public int getId () {return id; 
  The public void setId (int id) {this.id = ID; 
  Public String GetName () {return name; 
  public void SetName (String name) {this.name = name; Public String GetTitle () {RetuRN title; 
  public void Settitle (String title) {this.title = title; 
        @Override public String toString () {return "Teacher [id= + ID +", name= "+ name +", title= "+ title 
  + "]"; 

 } 
 
}

Note that a Tabledata entity class is defined here:

Import java.util.List; 
 
public class Tabledata { 
 
  private String tablename; 
 
  Private List Tabledata; 
 
  Public String Gettablename () {return 
    tablename; 
  } 
 
  public void Settablename (String tablename) { 
    this.tablename = tablename; 
  } 
 
  Public List Gettabledata () {return 
    tabledata; 
  } 
 
  public void Settabledata (List tabledata) { 
    this.tabledata = tabledata; 
  } 
} 

Test class:
(Look at the implementation of the JSON back to the object, here after two transformations, the first reversal of the result is that the map is not the object we expect, the map again into JSON and then to object, I refer to the Gson2.1 jar processing Normal, as if using Gson1.6 jar will be an error, So it is recommended to use the latest version)

Import java.util.ArrayList; 
Import Java.util.Date; 
 
Import java.util.List; 
Import Com.google.gson.Gson; 
 
Import Com.google.gson.reflect.TypeToken; public class GsonTest5 {/** * @param args */public static void main (string[] args) {//object to json--& 
    Gt;start Student student1 = new Student (); 
    Student1.setid (1); 
    Student1.setname ("Li Kun"); 
 
    Student1.setbirthday (New Date ()); 
    Student Student2 = new Student (); 
    Student2.setid (2); 
    Student2.setname ("Cao Guisheng"); 
 
    Student2.setbirthday (New Date ()); 
    Student Student3 = new Student (); 
    Student3.setid (3); 
    Student3.setname ("Liupo"); 
 
    Student3.setbirthday (New Date ()); 
    list<student> stulist = new arraylist<student> (); 
    Stulist.add (STUDENT1); 
    Stulist.add (Student2); 
 
    Stulist.add (STUDENT3); 
    Teacher teacher1 = new Teacher (); 
    Teacher1.setid (1); 
    Teacher1.setname ("rice teacher"); 
 
    Teacher1.settitle ("Professor"); Teacher teacher2 = new Teacher (); 
    Teacher2.setid (2); 
    Teacher2.setname ("Teacher Ding"); 
    Teacher2.settitle ("lecturer"); 
    list<teacher> teacherlist = new arraylist<teacher> (); 
    Teacherlist.add (Teacher1); 
 
    Teacherlist.add (TEACHER2); 
    Tabledata TD1 = new Tabledata (); 
    Td1.settablename ("Students"); 
 
    Td1.settabledata (stulist); 
    Tabledata TD2 = new Tabledata (); 
    Td2.settablename ("Teachers"); 
 
    Td2.settabledata (teacherlist); 
    list<tabledata> tdlist = new arraylist<tabledata> (); 
    Tdlist.add (TD1); 
    Tdlist.add (TD2); 
    Gson Gson = new Gson (); 
 
    String s = Gson.tojson (tdlist); 
    System.out.println (s); Results: [{"TableName": "Students", "tabledata": [{"id": 1, "name": "Li Kun", "Birthday": "June, 10:44:16 AM"},{"id": 2, " Name ":" Cao Guisheng "," Birthday ":" June, 10:44:16 AM "},{" id ": 3," name ":" Liupo "," Birthday ":" June, 10:44:16 AM ""}]},{" TableName ":" Teachers "," tabledata ": [{" id ": 1," name ":" M Teacher "," title ":" Professor "},{" ID ": 2," name ":" Teacher Ding "," title ":" Lecturer "}]//YesLike Json-->end/////////////////////////////////////////////////////////////////////////converting JSON to data--> 
        Start list<tabledata> TABLEDATAS2 = Gson.fromjson (S, new typetoken<list<tabledata>> () { 
    }.gettype ()); 
      for (int i = 0; i < tabledatas2.size (); i++) {Tabledata Entitydata = Tabledatas2.get (i); 
      String tablename = Entitydata.gettablename (); 
      List tabledata = Entitydata.gettabledata (); 
      String s2 = Gson.tojson (tabledata); 
      SYSTEM.OUT.PRINTLN (S2); 
      System.out.println (Entitydata.getdata ()); 
        if (Tablename.equals ("students")) {System.out.println ("students"); 
            list<student> retstulist = Gson.fromjson (s2, new typetoken<list<student>> () { 
        }.gettype ()); 
        for (int j = 0; J < Retstulist.size (); j + +) {System.out.println (Retstulist.get (j)); } else if (Tablename.equals ("Teachers")) {SYSTEM.OUT.PRINTLN ("teachers"); 
            list<teacher> rettchrlist = Gson.fromjson (s2, new typetoken<list<teacher>> () { 
        }.gettype ()); 
        for (int j = 0; J < Rettchrlist.size (); j + +) {System.out.println (Rettchrlist.get (j)); 

 Convert}}//JSON to object-->end}}

Output results:

[{"TableName": "Students", "tabledata": [{"id": 1, "name": "Li Kun", "Birthday": "June, 10:04:12 PM"},{"id": 2, "name": " Cao Guisheng "," Birthday ":" June, 10:04:12 PM "},{" id ": 3," name ":" Liupo "," Birthday ":" June, 10:04:12 PM "}]},{" tablename ": "Teachers", "tabledata": [{"id": 1, "name": "M Teacher", "title": "Professor"},{"ID": 2, "name": "Teacher Ding", "title": "Lecturer"}] 
Students 
Student [Birthday=fri June 22:04:12 CST, id=1, name= Li Kun] 
Student [Birthday=fri June 22:04:12 CST, id=2, Name= Cao Guisheng] 
Student [Birthday=fri June 22:04:12 CST, id=3, Name= Liupo] 
teachers 
Teacher [id=1, name= rice teacher, Professor Title=] 
Teacher [id=2, teacher Name=, title= lecturer] 

Registering typeadapter and handling enum types

Enumeration types are good for our programs, how do we use Gson to turn with JSON? Please see this article.

This article focuses on how to write your own typeadapter and register Typeadapter and handle enum types.

Entity classes:

Public enum Packagestate {play 
  , UPDATE, updating, DOWNLOAD, downloading, 
} public 

class Packageitem { 
  private String name; 
  Private packagestate State; 
  private String size; 
 
  Public String GetName () {return 
    name; 
  } 
 
  public void SetName (String name) { 
    this.name = name; 
  } 
 
  Public Packagestate GetState () {return state 
    ; 
  } 
 
  public void SetState (Packagestate state) { 
    this.state = state; 
  } 
 
  Public String GetSize () {return 
    size; 
  } 
 
  public void SetSize (String size) { 
    this.size = size; 
  } 
 
  @Override public 
  String toString () {return 
    "Packageitem [name=" + name + ", size=" + size + ", state=" 
        + S Tate + "]"; 
  } 
} 

Write yourself a converter to implement the Jsonserializer<t> interface and the Jsondeserializer<t> interface:

Import Java.lang.reflect.Type; 
Import Com.google.gson.JsonDeserializationContext; 
Import Com.google.gson.JsonDeserializer; 
Import com.google.gson.JsonElement; 
Import com.google.gson.JsonParseException; 
Import com.google.gson.JsonPrimitive; 
Import Com.google.gson.JsonSerializationContext; 
 
Import Com.google.gson.JsonSerializer; 
 
  public class Enumserializer implements Jsonserializer<packagestate>, jsondeserializer<packagestate> { Object to JSON, implements the Jsonserializer<packagestate> interface @Override public jsonelement serialize (packagestate state, T 
  ype arg1, Jsonserializationcontext arg2) {return new jsonprimitive (State.ordinal ());  The//JSON is invoked as an object, implementing the Jsondeserializer<packagestate> interface @Override public packagestate deserialize (jsonelement JSON, Type Typeoft, Jsondeserializationcontext context) throws Jsonparseexception {if (Json.getasint () < Packagestate.values (). Length) return packagestate.values () [JSON. Getasint ()]; 
  return null; 
 } 
 
}

Test class:

Import Com.google.gson.Gson; 
Import Com.google.gson.GsonBuilder; 
 
public class GsonTest6 {public 
 
  static void Main (string[] args) { 
    Gsonbuilder gsonbuilder = new Gsonbuilder (); 
   
    gsonbuilder.registertypeadapter (Packagestate.class, 
        new Enumserializer ()); 
    Gson Gson = Gsonbuilder.create (); 
    Packageitem item = new Packageitem (); 
    Item.setname ("Item_name"); 
    Item.setsize ("500M"); 
    Item.setstate (packagestate.updating);//This state is the enumeration value 
 
    String s = Gson.tojson (item); 
    System.out.println (s); 
 
    System.out.println ("--------------------------------"); 
 
    Packageitem Retitem = Gson.fromjson (s, packageitem.class); 
    System.out.println (Retitem); 
  } 
 


   


Output result (the result has converted the state's corresponding enum type to type int):

{' name ': ' Item_name ', ' state ': 2, ' size ': ' 500M '} 
-------------------------------- 
Packageitem [Name=item_name, size=500m, state=updating] 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.