Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JS date using Jackson?

I'm getting a date string from ExtJS in the format:

"2011-04-08T09:00:00"

when i try to deserialize this date, it changes the timezone to Indian Standard Time (adds +5:30 to the time) . This is how i'm deserializing the date:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat); 

Doing this also doesn't change the timezone. I still get the date in IST:

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); getObjectMapper().getDeserializationConfig().setDateFormat(dateFormat); 

How do I deserialize the date in the way in which it is coming without the hassles of Timezone?

like image 459
Varun Achar Avatar asked Apr 08 '11 07:04

Varun Achar


People also ask

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.

How do you deserialize a date?

This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);

How do I change the date format in object mapper?

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).


1 Answers

I found a work around but with this I'll need to annotate each date's setter throughout the project. Is there a way in which I can specify the format while creating the ObjectMapper?

Here's what I did:

public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {     @Override     public Date deserialize(JsonParser jsonParser,             DeserializationContext deserializationContext) throws IOException, JsonProcessingException {          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");         String date = jsonParser.getText();         try {             return format.parse(date);         } catch (ParseException e) {             throw new RuntimeException(e);         }      }  } 

And annotated each Date field's setter method with this:

@JsonDeserialize(using = CustomJsonDateDeserializer.class) 
like image 168
Varun Achar Avatar answered Sep 20 '22 15:09

Varun Achar