Simple to use Quick Start Jackson

 

1 Introduction

Jackson has a relatively high serialization and de-serialization efficiency, according to the test, either in the form of conversion, Jackson> Gson> Json-lib, and Jackson even higher processing capacity of nearly 10 times Json-lib, and correct It is also very high. In contrast, Json-lib seems to have stopped updating, the latest version is also based on JDK15, while Jackson community is more active.

Now, with examples to brief introduction to the use of Jackson's.

2 Use

Jackson provides many classes and methods, but most of the class in serialization and deserialization is ObjectMapper this class, which are more similar to Json-lib and JsonObject ArrayObject. Such provides readTree (), readValue (), writeValueAsString () for converting the like.
To avoid repeated description, objectMapper below are involved in regard to ObjectMapper objectMapper = new ObjectMapper (). The following were serialized and deserialized two aspects brief usage.

2.1 serialization
2.1.1 java classes own sequence of
Test Examples 2.1.1.1

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

2.1.1.2 achieve serialization

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

The results are output in the console:

[1,2,3]

2.1.1.3 Conclusion
Jackson serialization of the general type is simple and can be achieved.

2.1.2 custom serialization class
2.1.2.1 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; } } 

For example, more versatile, these include the value of type int, reference type String, String [], further comprising a date type Date.

2.1.2.2 achieve serialization

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

The results are output in the console:

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

2.1.2.3 Conclusion
By Json string output, the converted visible is in line format. However, the time expressed some do not meet the standards. The following describes changes to the format of the time.

2.1.3 format defined time
Jackson have their default time format, i.e. in the form of timestamps, i.e. the effect results shown above (e.g.: 1375429228382). If you want to set this format is invalid, by objectMapper.configure (SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false) can be provided, so that time would generate a so-called time -compliant notation, the output similar to the following format using [ISO-8601]: "1970-01-01T00: 00: 00.000 + 0000 ".

Of course, you can also be defined from the time the output format.

2.1.3.1 custom implementation time format
example also using 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);

Demerit is output on the console:

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

2.1.3.2 Conclusions
visible time output format became what we wanted. The method of the output format in Jackson lot simpler than the defined time period defined in the format in Json-lib.

Another sequence method 2.1.4
2.1.4.1 implement serialization
used example is still before 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 are:

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

2.1.4.2 Conclusion
This method can also obtain the value of the above process. Note that in this method but this function: createJsonGenerator (), it takes two parameters, a parameter OutputStream type, a parameter type is JsonEncoding. With these two parameters, we can understand that this method can not only Json written directly to the network stream, also Json can be written to a file or memory stream flow. So more versatile.

2.2 deserialization
2.2.1 disposable deserialize
this method provides mainly use ObjectMapper <testJsonClass> readValue (String content, Class <testJsonClass> valueType) method. This method requires an input Class Json string needs to be filled and corresponding to the class, the class returned after filling.

2.2.1.1 The Json stream analysis to custom class
when Json string is:
when String test1 = "{" objectID " : 357," geoPoints ": [{" x ":: 504604.59802246094," y "305569.9150390625}]}" .
First, a custom class:

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

Then use the following code segment Json to deserialize this class:

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

Using System.out.println (testClass.objectID); System.out.println (testClass.geoPoints) can see that the value of the output on the console:

357

[{X = 504604.59802246094, y = 305569.9150390625}]

2.2.1.2 The Json string deserializing system comes to the class
when the string is Json

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":[]}}"。

The system comes with the definition of a variable Map: Map <String, Map <String, Object >> maps. Then using maps = objectMapper.readValue (json, Map.class) can be deserialized to the variable Json the maps.

By System.out.println (maps.get ( "error")); System.out.println (. (Object) (maps.get ( "data") get ( "phone"))), may be obtained in the console the following results:

0

{home=abc, mobile=def}

2.2.2 gradually deserialize
this method is more flexible, Json string information values may be of interest to the user only extracted. To achieve the main use JsonNode class ObjectMapper provided readTree and Jackson offered.

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

This string Json complicated form comprises an array of nested, universal.

2.2.2.2 realize deserialization

JsonNode node= objectMapper.readTree(test);      //将Json串以树状结构读入内存

JsonNode contents=node.get("results");//得到results这个节点下的信息

for(int i=0;i<contents.size();i++) //遍历results下的信息,size()函数可以得节点所包含的的信息的个数,类似于数组的长度 { System.out.println(contents.get(i).get("objectID").getIntValue()); //读取节点下的某个子节点的值 JsonNode geoNumber=contents.get(i).get("geoPoints"); for(int j=0;j<geoNumber.size();j++) //循环遍历子节点下的信息 { System.out.println(geoNumber.get(j).get("x").getDoubleValue()+" "+geoNumber.get(j).get("y").getDoubleValue()); } } 

The results are output in the console:

357

504604.59802246094 305569.9150390625

358

504602.2680053711 305554.43603515625

2.2.2.3 knot *
This method is similar to the DOM XML parsing parse, its benefits are detailed structure, easy to extract the desired information. Of course, the drawback of this method and also the same: time-consuming space.

3. Summary

Jackson operation with respect to the main Json shown above, the method is very convenient to use, but also very flexible, providing a one-time operation performed, but also provides information on demand operation can be read. And Jackson's function is complete, it can control a variety of details of serialization and de-serialization, such as annotations and Hibernate inject the delay function and set the time format functions, because these functions are currently less desirable, so carefully studied until later. At the same time, Jackson also support a range of serialization and de-serialization of XML, which is roughly the same ideas and resolve the Json.

For Jackson the current shortcomings, the Internet was testing more than Json-lib some of total memory. And the use of space for time, is generally worth it.

History article:
JAVA micro-channel enterprises to change payment (ten minutes to get)

Original link (my blog migration)  https://blog.csdn.net/angryjiji/article/details/98265414

Guess you like

Origin www.cnblogs.com/angryjj/p/11291981.html