How to deserialize JS date using Jackson?
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)
There is a good blog about this topic:http://www.baeldung.com/jackson-serialize-dates Use @JsonFormat looks the most simple way.
public class Event { public String name; @JsonFormat (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss") public Date eventDate;}