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 }
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.
This is how i'm deserializing the date: SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); getObjectMapper(). getDeserializationConfig(). setDateFormat(dateFormat);
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.
Jackson is a powerful and efficient Java library that handles the serialization and deserialization of Java objects and their JSON representations.
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'"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With