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

How to customize JsonSerialize and Deserialize to realize data type conversion

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

How to customize JsonSerialize and Deserialize to achieve data type conversion, I believe that many inexperienced people do not know what to do, so this paper summarizes the causes of the problem and solutions, through this article I hope you can solve this problem.

1. LocalDateTime deserialization exception

First of all, we define a java POJO entity class, in which the key member variable is birthDate, we do not use the Date data type, but use the new Java8 date type LocalDateTime, I will not say much about the benefits of using LocalDateTime, there are many articles to explain. Let's return to Jackson's serialization and deserialization of content in JSON format.

[@ Data] (https://my.oschina.net/difrik)public class PlayerStar4 {private String name; / / name private LocalDateTime birthDate; / / date of birth}

In the following code, we first define an object player of the PlayerStar4 class, and then

Serialize a player object to a JSON string jsonString using the writeValueAsString method

Then use the readValue method to jsonString the JSON string, which is deserialized into an object of the PlayerStar4 class

[@ Test] (https://my.oschina.net/azibug)void testJSON2Object () throws IOException {ObjectMapper mapper = new ObjectMapper (); PlayerStar4 player = new PlayerStar4 (); player.setName ("curry"); / / I don't know Curry's birthday, here is a made-up player.setBirthDate (LocalDateTime.of (1986)); / / serialize player objects into String objects String jsonString = mapper.writeValueAsString (player); System.out.println (jsonString) in JSON format / / deserialize JSON strings into java objects PlayerStar4 curry = mapper.readValue (jsonString, PlayerStar4.class); System.out.println (curry);}

But the above code is wrong, as you can see from the following figure

The process of serializing the player object into the JSON string jsonString is performed normally, but the result of LocalDateTime serialization is the "yellow box in the yellow box" in the figure.

There was an error in the process of deserializing the JSON string, because by default, Jackson does not recognize the LocalDateTime serialized JSON string data structure of the "yellow box in the yellow box" content in the figure. It cannot be deserialized into a java object.

What shall I do? We need custom serialization and deserialization type converters. There are two ways

Inherit the StdConverter class and customize the conversion between String and LocalDateTime

Inherit JsonSerializer and JsonDeserializer classes, customize the conversion between String and LocalDateTime

Method 1: inherit the StdConverter class

Inherit the StdConverter class to serialize LocalDateTime to the String data type

Public class LocalDateTimeToStringConverter extends StdConverter {static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofLocalizedDateTime (FormatStyle.MEDIUM); @ Override public String convert (LocalDateTime value) {return value.format (DATE_FORMATTER);}}

Inherits the StdConverter class and deserializes the String data type to LocalDateTime

Public class StringToLocalDatetimeConverter extends StdConverter {@ Override public LocalDateTime convert (String value) {return LocalDateTime.parse (value, LocalDateTimeToStringConverter.DATE_FORMATTER);}}

Once the custom converter is complete, we can specify the serialization converter using @ JsonSerialize and the deserialization converter using @ JsonDeserialize on the corresponding member variables.

@ JsonSerialize (converter = LocalDateTimeToStringConverter.class) @ JsonDeserialize (converter = StringToLocalDatetimeConverter.class) private LocalDateTime birthDate

Then call the test case in the first section and there will be no exception. The console printout is as follows. The first line is the serialized result JSON format string, and the second line is the print result of the toString () method of the Java object.

{"name": "curry", "birthDate": "1986-4-5 12:50:00"} PlayerStar4 (name=curry, birthDate=1986-04-05T12:50) III. Method 2: inheriting JsonSerializer and JsonDeserializer classes

Inherit the JsonSerializer class to serialize LocalDateTime to the String data type

Public class LocalDateTimeSerializer extends JsonSerializer {static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofLocalizedDateTime (FormatStyle.MEDIUM); @ Override public void serialize (LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {String s = value.format (DATE_FORMATTER); gen.writeString (s);}}

Inherits the JsonDeserializer class and deserializes the String data type to LocalDateTime

Public class LocalDatetimeDeserializer extends JsonDeserializer {@ Override public LocalDateTime deserialize (JsonParser p, DeserializationContext ctx) throws IOException {String str = p.getText (); return LocalDateTime.parse (str, LocalDateTimeSerializer.DATE_FORMATTER);}} 4. If you don't understand anything above

For relatively rookie readers, you don't understand the above custom serialization and deserialization conversion process, and don't panic about LocalDateTime exceptions. Jackson has given a solution.

In particular, we need to emphasize that LocalDateTimeSerializer and LocalDateTimeDeserializer do not need to be defined by ourselves, because Jackson has already defined them for us. The reason why I also did a custom implementation of the introduction, because to explain this custom serialization and deserialization type conversion process, later you encounter other special data type conversion, or LocalDateTime type special date format, etc., you can define JsonSerialize and JsonDeserialize to achieve data type conversion.

The following two classes are LocalDateTimeSerializer and LocalDateTimeDeserializer that Jackson has defined for us.

Import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer

You can use @ JsonSerialize to specify the serialization converter and @ JsonDeserialize to specify the deserialization converter on the corresponding member variables.

@ JsonSerialize (using = LocalDateTimeSerializer.class) @ JsonDeserialize (using = LocalDateTimeDeserializer.class) private LocalDateTime birthDate

The serialization and deserialization results after execution are the same as those customized by method 1 and method 2.

After reading the above, have you mastered how to customize JsonSerialize and Deserialize to achieve data type conversion? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

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