In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
This article shows you what the basic core usage of Jackson is, which is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
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. Let's introduce the basic core usage of Jackson.
Read JSON data from URL
Jackson can not only deserialize a string into a Java POJO object, but also request a remote API, get the JSON response result of the remote service, and convert it into a Java POJO object.
[@ Test] (https://my.oschina.net/azibug)void testURL () throws IOException {URL url = new URL ("https://jsonplaceholder.typicode.com/posts/1"); / / remote service URL ObjectMapper mapper = new ObjectMapper (); / / get JSON response data from URL and deserialize it into java object PostDTO postDTO = mapper.readValue (url, PostDTO.class); System.out.println (postDTO);}
Jsonplaceholder.typicode.com is a website that provides HTTP testing service for free, and we can use it for testing.
The result returned by the remote service API is a JSON string, and a post contribution contains the userId,id,title,content attribute
PostDTO is our own defined java class, which also contains userId,id,title,content member variables
The following is the console printout, which is output by the toString () method of postDTO.
PostDTO (userId=1, id=1, title=sunt aut facere repellat provident occaecati excepturi optio reprehenderit, body=quia et suscipitsuscipit recusandae consequuntur expedita et cumreprehenderit molestiae ut ut quas totamnostrum rerum est autem sunt rem eveniet architecto) II. Unknow Properties assignment failure handling
Sometimes, the client provides more JSON string properties than the member variables of the java class defined by our server.
For example, the two classes in the figure above
Let's first serialize the PlayerStar into a JSON string, including the age attribute
Then convert the JSON string to PlayerStar2 without the age attribute
[@ Test] (https://my.oschina.net/azibug)void testUnknowProperties () throws IOException {ObjectMapper mapper = new ObjectMapper (); PlayerStar player = PlayerStar.getInstance (); / / assign values to each attribute of PlayerStar, you can refer to the first article in this series / / serialize PlayerStar into JSON string String jsonString = mapper.writeValueAsString (player); System.out.println (jsonString); / / deserialize JSON string into PlayerStar2 object PlayerStar2 player2 = mapper.readValue (jsonString, PlayerStar2.class) System.out.println (player2);}
When deserialization occurs, the following exception is thrown. This is because the attributes contained in the JSON string are superfluous with the definition of the Java class (there is an extra age and the setAge method cannot be found when assigning the value).
{"age": 45, "playerName": "Jordan"} com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "age" (class com.example.demo.javabase.PlayerStar2), not marked as ignorable (one known property: "playerName"]) at [Source: (String) "{" age ": 45," playerName ":" Jordan "}"; line: 1, column: 10] (through reference chain: com.example.demo.javabase.PlayerStar2 ["age"])
If we want to ignore the age attribute and not accept the undefined member variable data of our java class, we can use the following method so that UnrecognizedPropertyException is not thrown.
ObjectMapper mapper = new ObjectMapper (); mapper.disable (DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); III. Unassigned Java Bean serialization
Sometimes, we know that the data of some class may be empty, and we usually don't assign a value to it. But the client needs this {} JSON object. What should we do?
Public class MyEmptyObject {private Integer i; / / No get set method}
We can set the disable serialization feature for ObjectMapper: FAIL_ON_EMPTY_BEANS, which allows all properties of the object to be unassigned.
[@ Test] (https://my.oschina.net/azibug)void testEmpty () throws IOException {ObjectMapper mapper = new ObjectMapper (); mapper.disable (SerializationFeature.FAIL_ON_EMPTY_BEANS); String jsonString = mapper.writeValueAsString (new MyEmptyObject ()); System.out.println (jsonString);}
If it is not set by default, the following exception InvalidDefinitionException will be thrown. Set the disable serialization feature: after FAIL_ON_EMPTY_BEANS, it is serialized into a {} string.
Com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class com.example.demo.jackson.JacksonTest1 $MyEmptyObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) IV. Date formatting
Date formatting is a common requirement in the process of JSON serialization and deserialization.
ObjectMapper mapper = new ObjectMapper (); Map temp = new HashMap (); temp.put ("now", new Date ()); String s = mapper.writeValueAsString (temp); System.out.println (s)
By default, the serialization result of Jackson for dates and related types in java is as follows
{"now": 1600564582571}
If we want to format the date during JSON serialization and deserialization, we need to do the following
ObjectMapper mapper = new ObjectMapper (); mapper.disable (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); / / notice here mapper.setDateFormat (new SimpleDateFormat ("yyyy-MM-dd")); / / notice here Map temp = new HashMap (); temp.put ("now", new Date ()); String s = mapper.writeValueAsString (temp); System.out.println (s)
The printout result of the console is as follows:
{"now": "2020-09-20"} what are the basic core uses of Jackson? have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.