Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the core use of serialization and deserialization in the JSON data processing framework Jackson

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

What is the core use of serialization and deserialization in the JSON data processing framework Jackson? to solve this problem, this article introduces the corresponding analysis and solutions in detail, hoping to help more partners who want to solve this problem to find a simpler and easier way.

Jackson is the default JSON data processing framework for Spring Boot, but it does not depend on any Spring libraries. Some partners think that Jackson can only be used within the framework of Spring, but in fact, it is not, there is no such restriction. It provides a lot of JSON data processing methods and annotations, as well as streaming API, tree model, data binding, and complex data type conversion. Although it is easy to use, it is definitely not a small toy. The following is an introduction to the basic core usage of Jackson.

I. basic preparation

By introducing the following jar in any project, you can use jackson for data serialization and deserialization of JSON.

Com.fasterxml.jackson.core jackson-databind 2.9.8

Write a PlayerStar entity class, which mainly reflects the basketball star's name, age, hobbies, friends, annual income and other information. In order to demonstrate the serialization and deserialization function of Jackson as much as possible, array, List, Map are integrated into this class. And initialize the basketball star Jordan through getInstance.

[@ Data] (https://my.oschina.net/difrik)public class PlayerStar {private String name; private Integer age; private String [] hobbies; / / hobby, array private List friends; / / friend private Map salary; / / annual income Map / / initialize an object to test public static PlayerStar getInstance () {PlayerStar playerStar = new PlayerStar (); playerStar.setName ("Jordan"); playerStar.setAge (45) PlayerStar.setHobbies (new String [] {"golf", "baseball"}); Map salary = new HashMap () {{put ("2000", new BigDecimal (10000000)); put ("2010", new BigDecimal (62000000)); put ("2020", new BigDecimal (112400000));}; playerStar.setSalary (salary); playerStar.setFriends (Arrays.asList ("kobe", "curry", "james"); return playerStar) 2. Serialization method

The following code demonstrates how to serialize a PlayerStar object into a JSON string.

WriteValue can take File as a parameter to save the JSON serialization result to a file

WriteValueAsString returns the result of JSON serialization as String

The writerWithDefaultPrettyPrinter method can format the JSON serialization result, better display the structure, and is easy to view.

[@ Test] (https://my.oschina.net/azibug)void testObject2JSON () throws IOException {/ / get object instance PlayerStar player = PlayerStar.getInstance (); / ObjectMapper exists ObjectMapper mapper = new ObjectMapper () as the API utility class of Jackson; / / serialize the player object in JSON format and write the serialization result to the file mapper.writeValue ("d:\ data\\ jackson\ player.json"), player) / serialize player objects in JSON format into String objects String jsonString = mapper.writeValueAsString (player); System.out.println (jsonString); / / serialize player objects into String objects in JSON format (format beautification) String jsonInString2 = mapper.writerWithDefaultPrettyPrinter () .writeValueAsString (player); System.out.println (jsonInString2);}

The jsonString console printout result, which is also the content of the d:\ data\ jackson\ player.json file

{"name": "Jordan", "age": 45, "hobbies": ["golf", "baseball"], "friends": ["kobe", "curry", "james"], "salary": {"2000": 10000000, "2010": 62000000, "2020": 112400000}}

The console printout of jsonString2 is beautified because of the use of the writerWithDefaultPrettyPrinter () method

{"name": "Jordan", "age": 45, "hobbies": ["golf", "baseball"], "friends": ["kobe", "curry", "james"], "salary": {"2000": 10000000, "2010": 62000000, "2020": 112400000} 3.

The following code demonstrates how to deserialize a JSON string into a Java object

[@ Test] (https://my.oschina.net/azibug)void testJSON2Object () throws IOException {ObjectMapper mapper = new ObjectMapper (); / / read the JSON string from the file and deserialize the java object PlayerStar player = mapper.readValue (new File ("d:\ data\\ jackson\ player.json"), PlayerStar.class); System.out.println (player) / / deserialize JSON strings into java objects String jsonInString = "{\" name\ ":\" Jordan\ ",\" age\ ": 45,\" hobbies\ ": [\" Golf\ ",\" Baseball\ "]}"; PlayerStar jordan = mapper.readValue (jsonInString, PlayerStar.class); System.out.println (jordan);}

The output from the PlayerStar object console is as follows (note that the output here is not in JSON format, but rather the toString () method value of the java object):

PlayerStar (name= Jordan, age=45, hobbies= [golf, baseball], friends= [kobe, curry, james], salary= {2000,000,2010,62000,2020 million 112400000}) PlayerStar (name= Jordan, age=45, hobbies= [golf, baseball], friends=null, salary=null) IV, field rename @ JsonProperty

You can use @ JsonProperty to influence the renaming of serialization and deserialization object properties.

[@ Data] (https://my.oschina.net/difrik)public class PlayerStar {@ JsonProperty ("playerName") private String name; / / serializes the attribute name to playerName, while affecting deserialization

After using the annotations from the above code, the result of JSON serialization is that the name property becomes the playerName property.

{"playerName": "Jordan".

Also affecting deserialization, the following deserialization code reports an error because the name attribute is used. You should use playerName.

String jsonInString = "{\" name\ ":\" Jordan\ ",\" age\ ": 45,\" hobbies\ ": [\" Golf\ ",\" Baseball\ "]}"; PlayerStar jordan = mapper.readValue (jsonInString, PlayerStar.class); fifth, ignore the serialization of the null field @ JsonInclude

When we do not assign values to the member variables of the object, by default, the serialization result of the Jackson looks like this.

{"age": 45, "hobbies": null, "friends": null, "salary": null, "playerName": "Jordan"}

If we don't want the null value to be reflected in the JSON serialization result, we can use the following method. If you want to ignore the null member variable in the global scope of a serialization, you can use the following API

ObjectMapper mapper = new ObjectMapper (); mapper.setSerializationInclusion (JsonInclude.Include.NON_NULL)

Or add the following note to the class name. This annotation will take effect for all member variables in the class and will not be included in the serialization result as long as the member variable is null.

@ JsonInclude (JsonInclude.Include.NON_NULL) public class PlayerStar {.}

If we want to ignore null for some member variables in the PlayerStar class, we can comment on the member variables.

@ JsonInclude (JsonInclude.Include.NON_NULL) private String [] hobbies; / / hobby, array @ JsonInclude (JsonInclude.Include.NON_NULL) private List friends; / / friend @ JsonInclude (JsonInclude.Include.NON_NULL) private Map salary; / / annual income Map

When the member variable that is null is ignored, the result of JSON serialization is as follows

{"age": 45, "playerName": "Jordan"} VI. Ignore the specified field

By default, jackson does not serialize and deserialize member variables of static and transient. We can also pass through

@ JsonIgnore is added to the class member variable, which is excluded from the serialization and deserialization process

@ JsonIgnoreProperties is added to the class declaration to specify which fields in the class are excluded from the serialization and deserialization process

I can choose one of the two annotations above. I have used both annotations in the following code, and the functions are repeated.

@ Data@JsonIgnoreProperties ({"hobbies", "friends", "salary"}) public class PlayerStar {@ JsonProperty ("playerName") private String name; private Integer age; @ JsonIgnore private String [] hobbies; / / hobby, array @ JsonIgnore private List friends; / / friends @ JsonIgnore private Map salary; / / annual income Map.

After annotating the class or member variable, the serialization result is as follows, and the specified field is ignored.

{"age": 45, "playerName": "Jordan"}

It is important to note that these two annotations affect not only the process of serializing into JSON strings, but also the process of deserializing JSON strings into java objects. For example: if the JSON string contains the property value hobbies that is JsonIgnore in the class, it will not be deserialized to the member variable hobbies of the java object.

This is the answer to the question about what is the core use of serialization and deserialization in the JSON data processing framework Jackson. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report