When doing JSON deserialization, we may often pass a class object to get an example of the object. But sometimes, there may not be such a class object:
-
Template class. The object of the template class cannot be obtained directly. For example, class A<t> {}, using A<integer>.class will error. One solution would be to create a new class of EA extends a<integer>, so using Ea.class is possible. But this adds a lot of classes.
-
The object that needs to be serialized contains a base class reference member, which is referenced to a derived class. The information of the derived class is not getting deserialized. An optional idea is to add an annotation to the member explaining the possible derived class classes. Deserialization can be attempted on a per-annotation basis, selecting the correct derived class. Java seems to be an annotation that doesn't support mutable parameters.
Another way to solve these problems is to not define any classes that are accessed directly through Jsonarray and Jsonobject.
-
jsonarray is used to hold the JSON array. After successful parsing, if it is a Java built-in object, you can call the appropriate method to get the value, such as public Integer getinteger (int index). If it is not a built-in object, you can call public jsonobject getjsonobject (int index) to read the object. If you are still an array, you can call public jsonarray getjsonarray (int index). In fact, jsonarray is a list.
-
jsonobject Used to store non-built-in objects, organization is a key-value pair. In fact, the jsonobject is a map . After parsing succeeds, if it is a Java built-in object, you can call the appropriate method to get the value, such as ublic Integer Getinteger (String key). If it is not a built-in object, you can call public jsonobject getjsonobject (String key) to read the object. If you are still an array, you can call public Jsonarray Getjsonarray (String key).
By combining Jsonarray and jsonobject, we can access any deserialized JSON object without requiring the object's class information.
Example:
Import Com.alibaba.fastjson.json;import Com.alibaba.fastjson.jsonarray;public class Parsejsonobject {public static void main (String args[]) {string json = "[{\" id\ ": 1,\" type\ ": \" cycle\ ", \" attribute\ ": {\" center\ ": \" (10.4, 123.345) \ ", \ "Radius\": 67.4}},{\ "id\": 2,\ "type\": \ "polygon\", \ "attribute\": [{\ "vertex\": \ "(10.4, 133.345) \"}, {\ "vertex\": \ " (10.4, 143.345) \ "}]}]"; Jsonarray array = Json.parsearray (JSON); System.out.println (Array.getjsonobject (0). Getjsonobject ("attribute"). Get ("center")); System.out.println (Array.getjsonobject (1). Getjsonarray ("attribute"). Getjsonobject (1). Get ("vertex"));}}
The output is:
(10.4, 123.345)
(10.4, 143.345)
Fastjson's Jsonarray and Jsonobject