Simple use of Jackson, simple use of Jackson

Source: Internet
Author: User

Simple use of Jackson, simple use of Jackson
1 Overview

Jackson has high serialization and deserialization efficiency. According to tests, no matter which form of conversion, Jackson> Gson> Json-lib, in addition, Jackson's processing capability is about 10 times higher than that of Json-lib, And the correctness is also very high. In contrast, Json-lib seems to have stopped updating. The latest version is based on JDK15, while Jackson's community is more active.

Next, we will give a brief introduction to Jackson's usage using examples.

2. Use

Jackson provides many classes and methods, while the most frequently used classes in serialization and deserialization are the ObjectMapper class, which is similar to JsonObject and ArrayObject in Json-lib. This class provides methods such as readTree (), readValue (), and writeValueAsString () for conversion. For more information, see http://jackson.codehaus.org/1.7.9/javadoc/org/codehaus/jackson/map/objectmapper.html.

To avoid repeated descriptions, the objectMapper mentioned in the following section is about ObjectMapper objectMapper = new ObjectMapper (). The following describes the usage in terms of serialization and deserialization.

2.1 serialization 2.1.1 serialization of java built-in classes 2.1.1.1 test example

List list = new ArrayList ();

List. add (1 );

List. add (2 );

List. add (3 );

2.1.1.2 implement serialization

String teststringlist = objectMapper. writeValueAsString (list );

System. out. println (teststringlist );

The output result on the console is:

[1, 2, 3]

2.1.1.3 conclusion

Jackson can simply implement general type serialization.

2.1.2 serialization of custom classes 2.1.2.1 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 universal, This class includes the value type int, reference type String, String [], and Date type Date.

2.1.2.2 serialization

Student st = new student ();

String teststringstu = objectMapper. writeValueAsString (st );

System. out. println (teststringstu );

The output result on the console is:

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

2.1.2.3 conclusion

The output shows that the converted Json string is in the correct format. However, the representation of time is a bit out of standard. The following describes how to modify the time format.

2.1.3 definition of time format

Jackson has his own default time format, that is, the timestamps format. The effect is shown in the preceding result (for example, 1375429228382 ). If you want to set this format to invalid, use objectMapper. configure (SerializationConfig. feature. WRITE_DATES_AS_TIMESTAMPS, false) can be set, this will make time generation use the so-called use [ISO-8601]-compliant notation, output time similar to the following format: "1970-01-01T00: 00: 00.000 + 0000 ".

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

2.1.3.1 Implementation of custom time formats

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 output on the console is as follows:

{"List": ["hao", "haouhao", "keyi"], "time": "03:48:20," name ":" hhh "," age ": 10}

2.1.3.2 conclusion

It can be seen that the time output format is what we want. In Jackson, defining the time output format is much easier than defining the time format in Json-lib.

2.1.4 another serialization method 2.1.4.1 implement serialization

The example 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 result on the console is:

{"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 method. Note that the function createJsonGenerator () in this method requires two parameters: OutputStream and JsonEncoding. With these two parameters, we can understand that this method can not only directly write Json into the network stream, but also write Json into the file stream or memory stream. Therefore, it is widely used.

2.2 deserialization 2.2.1 One-time deserialization

This method mainly uses the <testJsonClass> readValue (String content, Class <testJsonClass> valueType) method provided by ObjectMapper. In this method, you need to enter the Json string and the Class of the Class to be filled, and return the filled Class.

2.2.1.1 parse Json strings into custom classes

When the Json string is:

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

First, define a class:

Public class testJsonClass

{

Public int objectID;

Public List geoPoints = new ArrayList ();

}

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

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

Use System. out. println (testClass. objectID); System. out. println (testClass. geoPoints) to view the output values on the console:

357

[{X = 504604.59802246094, y = 305569.9150390625}]

2.2.1.2 deserialize the Json string to the class that comes with the System

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

Use the built-in Map to define a variable: Map <String, Map <String, Object> maps. Then, you can use maps = objectMapper. readValue (json, Map. class) to deserialize Json to the variable maps.

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

2.2.2 progressive deserialization

This method is more flexible. You can extract only the Json string information values that you are interested in. It mainly uses the readTree provided by ObjectMapper and the JsonNode class provided by Jackson.

2.2.2.1 Test example

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 and contains nested arrays and is universal.

2.2.2.2 deserialization

JsonNode node = objectMapper. readTree (test); // read the Json string into the memory in a tree structure.

JsonNode contents = node. get ("results"); // obtain the information under the results node.

For (int I = 0; I <contents. size (); I ++) // traverses the information under results. The size () function can obtain 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 subnode under a node

JsonNode geoNumber = contents. get (I). get ("geoPoints ");

For (int j = 0; j <geoNumber. size (); j ++) // cyclically traverses information under the subnode

{

System. out. println (geoNumber. get (j ). get ("x "). getDoubleValue () + "" + geoNumber. get (j ). get ("y "). getDoubleValue ());

}

}

The output result in the console is:

357

504604.59802246094 305569.9150390625

358

504602.2680053711 305554.43603515625

2.2.2.3 conclusion

This method is similar to DOM parsing in XML parsing. Its advantage is structure details, which facilitates extraction of desired information. Of course, its disadvantage is also the same as this method: time-consuming and free-space.

3. Summary

Jackson's Json operations are mainly as shown above. The method is convenient to use and flexible, that is, it provides one-time operations and on-demand information reading operations. Jackson has complete functions to control serialization and deserialization details, such as the annotation function, the delay injection function for Hibernate, and the time format setting function, because these functions are not needed at present, you need to study them carefully. Jackson also supports a series of XML serialization and deserialization operations. The idea is roughly the same as that for Json parsing.

For Jackson's current shortcomings, some tests on the Internet occupy more memory than Json-lib. It is generally worthwhile to use space for time.


Easy to use.

Is used before a noun, but sometimes a noun can be omitted to form a noun phrase, for example:
His mother painted delicious food in the country. The Chinese people are insurmountable. The necklace I gave you was fake.
It must be used after a verb or adjective, for example:
This wild dish is so hot that you have a fever. (This must be used after the verb to indicate the possible meaning)
Place in front of verbs and adjectives, for example:
Listen quietly
I hope I can help you solve your doubts.

Simple PS usage

If you have time, go to the Internet to see the tutorial. Simple PS usage. For beginners who have no foundation, if you use text to describe, it is probably how to use the tool. Below is the PS shortcut.
1. Toolbox (if multiple tools share one shortcut key, you can press Shift to add this shortcut key at the same time)
Rectangular and elliptical box selection tool [M]
Mobile tool [V]
Loose, polygon, and magnetic loose [L]
Magic wand tool [W]
Cropping tool [C]
Slicing tool and selecting tool [K]
Spray gun tool [J]
Paint Brush tools and pencil tools [B]
Pictures and stamps (S]
History paint tools, art history paint brushes [Y]
Ripper, background erasure, and magic Ripper [E]
Gradient tool and paint bucket tool [G]
Blur, sharpen, and smear tools [R]
Fade-down, deepen, and Sponge tools [O]
Path selection tool and Direct selection tool []
Text tool [T]
Pen, free pen [P]
Rectangle, circle side rectangle, elliptic, polygon, straight line [U]
Comments on the board and sound [N]
Straw, color sampling device, measurement tool [I]
Hand capture tool [H]
Zooming tool [Z]
Default foreground color and background color [D]
Switch the foreground color and background color [X]
Switch between standard mode and quick masked mode [Q]
Standard Screen mode, full screen mode with menu bar, full screen mode [F]
Jump to "Ctrl" + "Shift" + "M" in ImageReady3.0]
Temporarily use the mobile tool Ctrl]
Temporary use of the color suction tool [Alt]
Temporarily use the hand capture tool [space]
Enter the tool option quickly (there must be at least one adjustable number in the current tool option panel) [0] to [9]
Cycle to select the paint brush [[] or []
Create a new gradient (in the gradient Editor) Ctrl + N]

Ii. File Operations
Create a graphic file Ctrl + N]
Open the existing image [Ctrl] + [O]
Open as... [Ctrl] + [Alt] + [O]
Close current image [Ctrl] + [W]
Save the current image Ctrl + S]
Save as... [Ctrl] + [Shift] + [S]
Save as a webpage graphic [Ctrl] + [Alt] + [Shift] + [S]
Set Ctrl + Shift + P on the page]
Print preview [Ctrl] + [Alt] + [P]
Print Ctrl + P]
Exit Photoshop [Ctrl] + [Q]

3. Edit operations
Restore/Redo the previous step operation [Ctrl] + [Z]
Step by step restore [Ctrl] + [Alt] + [Z]
Redo [Ctrl] + [Shift] + [Z] Step by Step]
Fade in/out Ctrl + Shift + F]
Cut the selected image or path Ctrl + X or F2]
Copy the selected image or path Ctrl + C]
Merge and copy [Ctrl] + [Shift] + [C]
Paste the content of the clipboard to the current image: Ctrl + V or F4]
Paste the content of the clipboard to the selected box Ctrl + Shift + V]
Free conversion [Ctrl] + [T]
Application free Transformation (in free Transformation Mode) [Enter]
Starting from the center or symmetric point (in the free Transformation Mode) [Alt]
Limitation (in free Transformation Mode) [Shift]
Twist (in free conversion mode) [Ctrl]
Cancel deformation (in free conversion mode) [Esc]
Convert and copy pixel data freely [Ctrl] + [Shift] + [T]
Change the copied pixel data again and create a copy Ctrl + Shift + Alt + T]
Delete the pattern in the selection box or select the path DEL]
Fill the selected area or entire layer with the background color Ctrl + BackSpace or Ctrl + Del]
Fill the selected area with the foreground color or the entire... the remaining full text>

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.