Commonly used conversion operations for structures such as List and map can basically meet most of the needs we handle, but sometimes there are special format regulations 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 ordinary methods are not easy to deal with the above json string. Please see how this article handles it:
Entity Class:
import java.util.Date; public class Student { private int id; private String name; private Date birthDay; public int getId() { return id; } 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; } 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; } 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 + ",]"; } }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 carefully at the implementation of converting json back to an object. After two conversions here, the result of the first rewinding is that map is not the object we expect. After converting map to json again, then converting it to an object. What I quoted is that the jar of Gson2.1 is handled normally. It seems that using the jar of Gson1.6 will report 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) { // Convert the object to Json-->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("Liu Bo"); 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("Teacher Mi"); 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); // Result:[{"tableName":"students","tableData":[{"id":1,"name":"Li Kun","birthDay":"Jun 22, 2012 10:44:16 AM"},{"id":2,"name":"Cao Guisheng","birthDay":"Jun 22, 2012 10:44:16 AM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 10:44:16 AM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 10:44:16 AM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"Teacher Mi","title":"Professor"},{"id":2,"name":"Teacher Ding","title":"Lecturer"}]}] // Convert the object to Json-->end // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 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)); } } } // Json is converted to an object -->end } }Output result:
[{"tableName":"students","tableData":[{"id":1,"name":"Li Kun","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":2,"name":"Cao Guisheng","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 10:04:12 PM"},{"id":3,"name":"Liu Bo","birthDay":"Jun 22, 2012 10:04:12 PM"}]},{"tableName":"teachers","tableData":[{"id":1,"name":"Teacher Mi","title":"Professor"},{"id":2,"name":"Teacher Ding","title":"Lecturer"}]}] students Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=1, name=Li Kun] Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=2, name=Cao Guisheng] Student [birthDay=Fri Jun 22 22:04:12 CST 2012, id=3, name=Liu Bo] teachers Teacher [id=1, name=Teacher Mi, title=Professor] Teacher [id=2, name=Teacher Ding, title=Lecturer]Register TypeAdapter and handle Enum types
Enumeration types bring benefits to our program. How to use Gson to achieve interchange with Json? Please see this article.
This article focuses on how to write a TypeAdapter yourself, register TypeAdapter and handle Enum types.
Entity Class:
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=" + state + "]"; } }Write a converter yourself to implement the JsonSerializer<T> interface and 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.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; public class EnumSerializer implements JsonSerializer<PackageState>, JsonDeserializer<PackageState> { // Called when the object is converted to Json, implementing JsonSerializer<PackageState> interface @Override public JsonElement serialize(PackageState state, Type arg1, JsonSerializationContext arg2) { return new JsonPrimitive(state.ordinal()); } // Called when the object is converted to 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);// 这个state是枚举值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 corresponding enumeration type of state has been converted to int type in the result):
{"name":"item_name","state":2,"size":"500M"} ----------------------------------------- PackageItem [name=item_name, size=500M, state=UPDATING]