Just to recap, serialization and deserialization is the process of converting to/from json. For instance, you may have json array that you want to convert to an arraylist using jackson. Or you could perform the same conversion with gson. When a user would post to a service or if we consume json by reading in a file we would take the json and convert it to a java object. When a date is read, we would want it to be parsed as a date not as a string.
To do this we will create a custom jackson deserializer by extending UntypedObjectDeserializer, a deserializer implementation used if it is necessary to bind content of an unknown type. We will first check if the token is a string and if it is use apache commons parse date passing in multiple formats. If an exception is thrown we will just parse using the context.
Once the deserializer is registered we must instruct ObjectMapper how we want to proceed if it hits a date. In Jackson 1.7, modules were introduced to extend jackson functionality so we can create a SimpleModule and register our CustomDateDeseralizer class.
Registering ObjectMapper with spring boot
If you are using spring boot, it configures an ObjectMapper automatically for you. To override default configuration simply create a bean called objectMapper and supply your configuration. It might look something like this:
Creating a sample json with a string and two dates we will want to run this through the ObjectMapper and verify that it creates java.util.date objects. When calling objectMapper.readValue we will specify that the json keys and values will be collected in a HashMap. Next looping through the entries we will output the key, value and the value class type.
Sample JSON
Program
Output
Thanks for joining in today's level up, have a great day!