Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Jackson Timezone for Date deserialization

I'm using Jackson (via Spring MVC Annotations) to deserialize a field into a java.util.Date from JSON. The POST looks like - {"enrollDate":"2011-09-28T00:00:00.000Z"}, but when the Object is created by Spring & Jackson it sets the date as "2011-09-27 20:00:00".

How can I set the proper timezone in Jackson? Or if that is not the problem, how do I send EST from the JSON message?

Javascript/jQuery:

var personDataView = { enrollDate : new Date($("#enrollDate").val()),                         //...other members                       };   $.postJSON('/some/path/', personDataView, function(data){     //... handle the response here  }); 

JSON Message:

{"enrollDate":"2011-09-28T00:00:00.000Z"}

Spring Controller:

@RequestMapping(value="/", method=RequestMethod.POST) public @ResponseBody String saveProfile(@RequestBody personDataView persondataView, HttpServletRequest request) {         //...dataView has a java.util.Date enrollDate field         //...other code } 
like image 903
Mike G Avatar asked Sep 26 '11 14:09

Mike G


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 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 Jackson serialization and deserialization?

Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations.


1 Answers

In Jackson 2+, you can also use the @JsonFormat annotation:

@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSSZ", timezone="America/Phoenix") private Date date; 

If it doesn't work this way then try wrapping Z with single quotes, i.e. pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

like image 115
Olivier Lecrivain Avatar answered Sep 28 '22 09:09

Olivier Lecrivain