Example analysis of Jackson's usage

  • 2020-04-01 03:24:05
  • OfStack

In layman's terms, Jackson is a Java class library for handling json-formatted data, which performs very well. This article will make a detailed example analysis of Jackson's usage. The details are as follows:

A list,

Jackson has relatively high serialization and deserialization efficiency, according to tests, regardless of which form of conversion, Jackson > Gson > Json-lib, and Jackson's processing power is even nearly 10 times higher than json-lib, and the correctness is also very high. In contrast, json-lib seems to have stopped updating, the latest version is also based on JDK15, and Jackson's community is more active.
The following is a brief introduction to Jackson's usage with an example.

Second, the use of

Jackson provides many classes and methods, and the most used class for serialization and deserialization is the ObjectMapper class, which is similar to JsonObject and ArrayObject in json-lib. Methods such as readTree(), readValue(), and writeValueAsString() are provided in this class for transformation. Specific documentation about such address is: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html.

In order to avoid repeating the description, the objectMapper mentioned below is referred to as objectMapper = new objectMapper (). The use is briefly described in terms of serialization and deserialization.

1. The serialization

(1) serialize the Java native class

Test cases


List list=new ArrayList();
list.add(1);
list.add(2);
list.add(3);

Achieve serialization:


String teststringlist=objectMapper.writeValueAsString(list);
System.out.println(teststringlist);

The output result in the console is:


[1,2,3]

Conclusion:

Jackson's serialization of general types is easy to implement.

(2) serialization of the custom class

Test examples:


public class student {
private int age=10;
private String name="hhh"; 
  public String[] list={"hao","haouhao","keyi"};
  public Date time=new Date();
     public int getAge() {
          return age;
     }
     public void setAge(int age) {
          this.age = age;
     }
     public String getName() {
          return name;
     }
     public void setName(String name) {
          this.name = name;
     }
}

To make the example more generic, this class contains the value type int, the reference type String, String[], and the Date type Date.
Implement serialization


student st=new student();
String teststringstu=objectMapper.writeValueAsString(st);
System.out.println(teststringstu);

The output result in the console is:


{"list":["hao","haouhao","keyi"],"time":1375429228382,"name":"hhh","age":10}

Conclusion:

Through the output, you can see that the resulting Json string is formatted. However, the timing is a bit off the mark. The changes to the time format are described below.

The definition of time format

Jackson has its own default time format, timestamps, with the effect shown above (for example: 1375429228382). If you want to set this format is invalid, pass


objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false)

Can be set so that the time is generated using the so-called iso-8601-compliant notation to output a time similar to the following format: "1970-01-01 t00:000.000 +0000".

Of course, you can also customize the time format of the output.

Custom time format implementation

The example also takes the student class described above.


student st=new student();
java.text.DateFormat myFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
objectMapper.getSerializationConfig().setDateFormat(myFormat);
String teststringstu=objectMapper.writeValueAsString(st);
System.out.println(teststringstu);

The demerit output from the console is:


{"list":["hao","haouhao","keyi"],"time":"2013-08-02 03:48:20","name":"hhh","age":10}

Conclusion:

So the time output format becomes what we want. The way to define the time output format in Jackson is much easier than the way to define the time format in json-lib.

Another method of serialization

Implement serialization

The example is still the student class.


student st=new student();
JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);
jsonGenerator.writeObject(st); 
System.out.println();

The output result of the console is:


{"list":["hao","haouhao","keyi"],"time":1375429228382,"name":"hhh","age":10}

Conclusion:

This method also yields the value of the above method. But notice the function in this method: createJsonGenerator (), which takes two arguments, one of type OutputStream and one of type JsonEncoding. With these two parameters, you can see that this method not only writes Json directly to a network stream, but also to a file stream or memory stream. So it's more versatile.

2. Deserialization

One-time deserialization

This approach mainly utilizes the < provided by ObjectMapper. TestJsonClass> ReadValue (String content, Class< TestJsonClass> ValueType) method. This method requires you to enter a Json string and the corresponding Class of the Class to be populated, returning the populated Class.
Parse the Json string into the custom class

When the Json string is:


String test1="{"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.9150390625}]}"

From time to time.

Start by customizing a class:


public class testJsonClass
 {
    public int objectID;
    public List geoPoints=new ArrayList();
}

Then deserialize Json to this class with the following code:


testJsonClass testClass= objectMapper.readValue(test1, testJsonClass.class);

using


System.out.println(testClass.objectID);
System.out.println(testClass.geoPoints)

The output value can be seen in the console as:


357
[{x=504604.59802246094, y=305569.9150390625}]

Deserialize the Json string to a class that comes with the system
When a Json string is


String json = "{"error":0,"data":{"name":"ABC","age":20,"phone":{"home":"abc","mobile":"def"},"friends":[{"name":"DEF","phone":{"home":"hij","mobile":"klm"}},{"name":"GHI","phone":{"home":"nop","mobile":"qrs"}}]},"other":{"nickname":[]}}" . 

Use the built-in Map to define a variable: Map< String, Map< String, Object> >   Maps. You can then deserialize json to the variable maps using maps = objectmapper.readvalue (json, map.class).
through


System.out.println(maps.get("error"));
System.out.println((Object)(maps.get("data").get("phone")))

The following results can be obtained in the console:


0
{home=abc, mobile=def}

(2) gradual deserialization

This method is more flexible and can extract only the Json string information values that the user is interested in. It is implemented by readTree provided by ObjectMapper and JsonNode class provided by Jackson.

Test cases


String test="{"results":[{"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.9150390625}]},{"objectID":358,"geoPoints":[{"x":504602.2680053711,"y":305554.43603515625}]}]}";

This Json string is complex, contains nested arrays, and is versatile.

Implement deserialization


JsonNode node= objectMapper.readTree(test);   //Read the Json string into memory as a tree
JsonNode contents=node.get("results");//Get the information under the results node
for(int i=0;i<contents.size();i++) //Through the information under results, the size() function can get the number of information contained in the node, similar to the length of the array
{
System.out.println(contents.get(i).get("objectID").getIntValue()); //Reads the value of a child node under the node
JsonNode geoNumber=contents.get(i).get("geoPoints");
for(int j=0;j<geoNumber.size();j++)   //Loop through the information under the child node
{
System.out.println(geoNumber.get(j).get("x").getDoubleValue()+" "+geoNumber.get(j).get("y").getDoubleValue());
}
}

The output result under the console is:


357
504604.59802246094 305569.9150390625
358
504602.2680053711 305554.43603515625

Conclusion:

This approach is similar to DOM parsing in XML parsing, and has the advantage of a detailed structure that makes it easy to extract the desired information. Of course, the downside is the same: it takes time and space.

3. To summarize

Jackson's approach to Json is as shown above, and it is convenient and flexible to use, providing both one-time operations and operations that can be read on demand. Moreover, Jackson has a full range of features, including detailed control over serialization and deserialization, such as annotations, deferred injection for Hibernate, and time formatting, etc., which are not needed at the moment, so we'll look into them later. Jackson also supports a series of serialization and deserialization operations for XML in much the same way as parsing Json.
For Jackson's current shortcomings, some people on the web tested that json-lib took up more memory than json-lib. And the use of space for time, is generally worth it.


Related articles: