Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson 2.3.2: Issue with deserializing a Date despite of setting the date format to ObjectMapper

I am using rest easy and want to serialize and deserialize dates.

After creating my json provider, Serializing is working fine but deserializing is still not working.

My JsonProvider class:

@Provider
@Produces(MediaType.APPLICATION_JSON)
public class JsonProvider extends JacksonJaxbJsonProvider {

   public JsonProvider() {

      ObjectMapper mapper = new ObjectMapper();
      mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
      mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
      mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      mapper.setDateFormat("dd MMM, yyyy hh:mm:ss a";

      super.setMapper(mapper);
   }
}

Input date: 09 Sep, 2014 11:00:00 AM

Error: com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of java.util.Date from String value '09 Sep, 2014 11:00:00 AM': not a valid representation (error: Failed to parse Date value '09 Sep, 2014 11:00:00 AM': Can not parse date "09 Sep, 2014 11:00:00 AM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

I came across this workaround but if I use this then I have to annotate every date field in my app which I feel is an overhead.

I am not able to figure out what I am doing wrong.

Any help would be appreciated.

Thanks.

like image 394
jcoder Avatar asked Sep 11 '14 17:09

jcoder


People also ask

How do I change the date format in ObjectMapper?

We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.

What is the default date format in Jackson?

It's important to note that Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC).

How does Jackson deserialize dates from JSON?

How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.

Why do we use ObjectMapper in Java?

ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model ( JsonNode ), as well as related functionality for performing conversions.


1 Answers

I got the same error, this solved my problem

mapper.setDateFormat(myDateFormat)

http://wiki.fasterxml.com/JacksonFAQDateHandling

like image 60
Niamath Avatar answered Oct 14 '22 04:10

Niamath