In layman's terms, Jackson is a Java class library used to process JSON format data, and its performance is very good. This article will give a more detailed example analysis of the usage of Jackson. The details are as follows:
1. Introduction
Jackson has relatively high serialization and deserialization efficiency. According to tests, no matter what form of conversion, Jackson > Gson > Json-lib, and Jackson's processing power is even nearly 10 times higher than Json-lib, and it is correct Sex is also very high. In contrast, Json-lib seems to have stopped updating, and the latest version is also based on JDK15, while the Jackson community is more active.
Below, we will briefly introduce the usage of Jackson with examples.
2. Use
Jackson provides many classes and methods, and the most commonly used class in serialization and deserialization is the ObjectMapper class, which is similar to JsonObject and ArrayObject in Json-lib. This class provides methods such as readTree(), readValue(), writeValueAsString() for conversion. The specific documentation address for this class is: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html.
In order to avoid repeated descriptions, the objectMapper mentioned below all comes from ObjectMapper objectMapper = new ObjectMapper(). The usage will be briefly introduced below in terms of serialization and deserialization.
1. Serialization
① Serialize Java’s own classes
Test example
List list=new ArrayList();list.add(1);list.add(2);list.add(3);
Implement serialization:
String teststringlist=objectMapper.writeValueAsString(list);System.out.println(teststringlist);
The result output on the console is:
[1,2,3]
in conclusion:
Jackson can easily implement serialization of general types.
②Serialization of custom classes
Test example:
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 general, this class includes 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 result output on the console is:
{"list":["hao","haouhao","keyi"],"time":1375429228382,"name":"hhh","age":10}
in conclusion:
Through the output, it can be seen that the converted Json string conforms to the format. However, the representation of time is a bit substandard. Modifications to the time format will be introduced below.
③Definition of time format
Jackson has its own default time format, which is in the form of timestamps, and its effect is as shown in the above results (for example: 1375429228382). If you want to set this format is invalid, pass
objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false)
It can be set so that the time generation uses so-called [ISO-8601 ]-compliant notation, outputting a time similar to the following format: "1970-01-01T00:00:00.000+0000".
Of course, you can also customize the output time format.
Implementation of custom time format
The example also uses the student class introduced 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 on the console is:
{"list":["hao","haouhao","keyi"],"time":"2013-08-02 03:48:20","name":"hhh","age":10}
in conclusion:
It can be seen that the time output format has become what we want. The method of defining the time output format in Jackson is much simpler than defining the time format in Json-lib.
④ Another serialization method
Implement serialization
The example used is still the previous student class.
student st=new student();JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);jsonGenerator.writeObject(st); System.out.println();
The output on the console is:
{"list":["hao","haouhao","keyi"],"time":1375429228382,"name":"hhh","age":10}
in conclusion:
This method can also get the value of the above method. But pay attention to this function in this method: createJsonGenerator(), which requires two parameters, one is the OutputStream type parameter and the other is the JsonEncoding type parameter. Through these two parameters, we can understand that this method can not only write Json directly to the network stream, but also write Json to the file stream or memory stream. So it’s more versatile.
2. Deserialization
①One-time deserialization
This method mainly uses the <testJsonClass> readValue(String content, Class<testJsonClass> valueType) method provided by ObjectMapper. This method requires inputting a Json string and the corresponding Class of the class that needs to be filled, and returns the filled class.
Parse Json string into custom class
When the Json string is:
String test1="{"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.9150390625}]}"
time.
First define a class:
public class testJsonClass { public int objectID; public List geoPoints=new ArrayList();}
Then use the following code snippet to deserialize Json into this class:
testJsonClass testClass= objectMapper.readValue(test1, testJsonClass.class);
use
System.out.println(testClass.objectID);System.out.println(testClass.geoPoints)
The values you can see output on the console are:
357[{x=504604.59802246094, y=305569.9150390625}]
Deserialize the Json string into the system's own class. When the 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":[]}}".
Define a variable using the system's own Map: Map<String, Map<String, Object>> maps. Then use maps = objectMapper.readValue(json, Map.class) to deserialize Json into the variable maps.
pass
System.out.println(maps.get("error"));System.out.println((Object)(maps.get("data").get("phone")))
You can get the following results in the console:
0{home=abc, mobile=def}
②Gradual deserialization
This method is more flexible and can extract only the Json string information value that the user is interested in. It is mainly implemented using the readTree provided by ObjectMapper and the JsonNode class provided by Jackson.
Test example
String test="{"results":[{"objectID":357,"geoPoints":[{"x":504604.59802246094,"y":305569.915039 0625}]},{"objectID":358,"geoPoints":[{"x":504602.2680053711,"y":305554.43603515625}]}]}";
This Json string is relatively complex, including the form of nested arrays, and is universal.
Implement deserialization
JsonNode node= objectMapper.readTree(test); //Read the Json string into the memory in a tree structure JsonNode contents=node.get("results");//Get the information under the results node for(int i=0; i<contents.size();i++) //Traverse 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()); //Read 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 nodes {System.out.println(geoNumber.get(j).get("x").getDoubleValue()+" " +geoNumber.get(j).get("y").getDoubleValue());}}
The output on the console is:
357504604.59802246094 305569.9150390625358504602.2680053711 305554.43603515625
in conclusion:
This method is similar to DOM parsing in XML parsing. The advantage is that the structure is detailed, making it easy to extract the desired information. Of course, the disadvantage is the same as this method: it takes time and space.
3. Summary
Jackson's operations on Json are mainly as shown above. Its method is very convenient to use and very flexible. It provides one-time operations and operations that can read information on demand. And Jackson has a full range of functions, which can control serialization and deserialization in various details, such as annotation function, delayed injection function for Hibernate, and setting time format function. Because these functions are not currently needed, study it carefully. Leave that for later. At the same time, Jackson also supports a series of serialization and deserialization operations on XML. The idea is roughly the same as parsing Json.
Regarding the current shortcomings of Jackson, some people on the Internet have tested that it takes up more memory than Json-lib. Using space for time is generally worth it.