Detailed explanation of advanced examples of converting Java objects into JSON objects using gson Library

Common conversion operations for list, map and other structures can basically meet most of our needs, but sometimes there are special format requirements for JSON in the project For example, the following JSON string parsing:

[{"tablename": "students", "tabledata": [{"Id": 1, "name": "Li Kun", "birthday": "Jun 222012 9:54:49 PM"}, {"Id": 2, "name": "Cao Guisheng", {"Id": 3, "name": "Liu Bo", 2012 9:54:49 PM "}]}, {" tablename ":" teachers "," name ":" teacher Mi "," title ":" Professor "}," name ":" teacher Ding "," title ":" lecturer "}]}]

After analysis, we found that ordinary methods are not easy to handle the above JSON string Please see how this article deals with it:

Entity class:

Note that a tabledata entity class is defined here:

Test class: (take a closer look at the implementation of turning JSON back into an object. After two transformations, the result of the first transformation is that the map is not the object we expect. Turn the map into JSON again and then into an object. I refer to the jar of gson2.1. The processing is normal. It seems that using the jar of gson1.6 will report an error, so it is recommended to use the latest version)

Output results:

Register typeadapter and handle enum type

Enumeration types bring benefits to our program. How to use gson to realize the mutual conversion with JSON? Please read this article

This article focuses on how to write a typeadapter, register a typeadapter and handle enum types

Entity class:

Write a converter to implement the jsonserializer < T > interface and jsondeserializer < T > interface:

Test class:

Output result (the corresponding enumeration type of state has been converted to int type in the result):

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>