A case study of Jackson's usage _java

Source: Internet
Author: User
Tags serialization

In layman's terms, Jackson is a class library that Java uses to process data in JSON format, and its performance is very good. This paper is to do a more detailed example analysis of the use of Jackson. Specifically as follows:

First, Introduction

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

Second, the use

Jackson offers a number of classes and methods, while the most used classes in serialization and deserialization are Objectmapper this class, which is similar to the Json-lib Jsonobject and Arrayobject. A method such as Readtree (), ReadValue (), writevalueasstring () is provided in this class for conversion. Specific description of this class documentation address is: http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/ObjectMapper.html.

To avoid repetitive descriptions, the following objectmapper are all about objectmapper Objectmapper = new Objectmapper (). The following is a brief description of the usage in two aspects of serialization and deserialization.

1. Serialization of

① serialization of Java self-band classes

Test examples

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

Implementing Serialization:

String teststringlist=objectmapper.writevalueasstring (list);
System.out.println (teststringlist);

The results of the output from the console are:

[1,2,3]

Conclusion:

Jackson can simply implement serialization of a generic type .

② 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 generic, this class contains the value type int, the reference type string,string[], and the date type dates.
Implementing serialization

Student st=new student ();
String teststringstu=objectmapper.writevalueasstring (ST);
System.out.println (Teststringstu);

The results of the output from the console are:

{' list ': [' Hao ', ' Haouhao ', ' keyi '], ' time ': 1375429228382, ' name ': ' HHH ', ' Age ': 10}

Conclusion:

Through the output, the resulting JSON string is well-formed. However, the presentation of time is somewhat inconsistent with the criteria. The changes to the time format are described below.

③ Definition of time format

Jackson has his own default time format, the timestamps form, whose effect is as shown on the result (for example, 1375429228382). If you want to set this format to be invalid, pass the

Objectmapper.configure (SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, False)

Can be set so that the time generation uses the so-called [ISO-8601]-compliant notation, which outputs a time similar to the following format: "1970-01-01t00:00:00.000+0000".

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

Implementation of custom time format

The example also uses 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 of the output of the control table is:

{"List": ["Hao", "Haouhao", "Keyi"], "Time": "2013-08-02 03:48:20", "name": "HHH", "Age": 10}

Conclusion:

The visible time output format becomes what we want. The method of defining the time output format in Jackson is much simpler than the definition of time format in Json-lib .

④ Another method of serialization

Implementing 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}

Conclusion:

This method can also get the value of the above method. But notice this function in this method: Createjsongenerator (), it takes two parameters, one is the OutputStream type parameter, the other is the jsonencoding type parameter. With these two parameters, we can see that this method not only writes JSON directly to the network stream, but also writes JSON to the file stream or to the memory stream. So it's a wider use.

2. Deserialization

① One-time deserialization

This method mainly utilizes the <testJsonClass> readvalue (String content, class<testjsonclass> ValueType) method provided by Objectmapper. This method needs to enter the JSON string and the corresponding class of the classes that need to be populated, returning the populated class.
Parsing a JSON string into a custom class

When the JSON string is:

String test1= "{ObjectID": 357, "geopoints": [{"X": 504604.59802246094, "y": 305569.9150390625}]} "

The time.

First customize a class:

public class Testjsonclass
 {public
    int objectID;
    Public List geopoints=new ArrayList ();
}

Then deserialize the JSON into this class using the following code:

Testjsonclass testclass= objectmapper.readvalue (test1, Testjsonclass.class);

Use

System.out.println (Testclass.objectid);
System.out.println (testclass.geopoints)

You can see the output values on the console as:

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": "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 with a Map of the system itself: map<string, map<string, object>> maps. The JSON can then be deserialized into variable maps using maps = Objectmapper.readvalue (JSON, Map.class).
Pass

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}

② Gradual deserialization

This method is more flexible and can extract only the JSON string information values that are of interest to the user. The main use of objectmapper provided by the Readtree and Jackson provided Jsonnode class to achieve.

Test examples

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 more complex and contains the form of nested arrays, which is universal.

Implementing deserialization

Jsonnode node= objectmapper.readtree (test);   Reads the JSON string in a tree structure into memory
Jsonnode contents=node.get ("results");//Gets the information for the results under this 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 ()); Reads the value of a child node under a node
jsonnode geonumber=contents.get (i). Get ("geopoints");
for (int j=0;j<geonumber.size (); j + +)   //looping through the information under the child node
{
System.out.println (Geonumber.get (j). Get ("X" ). Getdoublevalue () + "" +geonumber.get (j). Get ("Y"). Getdoublevalue ());


The results of the output under the console are:

357
504604.59802246094 305569.9150390625
358
504602.2680053711 305554.43603515625

Conclusion:

This method is similar to the DOM parsing in XML parsing, and its benefit is the structure detail, which makes it easy to extract the desired information. Of course, its disadvantages are the same as this: time-consuming cost space.

Three. Summary

Jackson's work on JSON, as shown above, is easy to use and flexible, providing a one-time complete operation, as well as an operation to read information on demand. And Jackson's function is complete, the serialization and deserialization can be a variety of details of the control, such as the annotation function and for the Hibernate delay injection function and set the time format features, because these features are not currently needed, so careful study for later. At the same time, Jackson supports a series of serialization and deserialization operations on XML, in much the same way as parsing JSON.
for Jackson's current shortcomings, people on the Web test more than json-lib more memory. And the use of space to change time, is generally worthwhile.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.