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.
Thanks for joining in today's level up, have a great day!