I am trying to convert a JSON present inside a file into a Java Object using ObjectMapper.
JSON file: sample-date-str.json
{
"eventDate"="2017-06-27 10:04:26.573503+05:30"
}
Java POJO: SampleDatePOJO
class SampleDatePOJO{
private Date eventDate;
getter and setter....
toString...
}
Java code for converting JSON to Java object:
ObjectMapper mapper = new ObjectMapper();
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSX")); //this will convert Date to IST format which is okay.
SampleDatePOJO sampleDatePOJO = mapper.readValue(new File("sample-date-str.json"), SampleDatePOJO.class);
System.out.println(sampleDatePOJO.getEventDate()); //this gives output "Tue
Jun 27 10:43:59 IST 2017"
Note: If I remove mapper.setDateFormat(..) and use @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSSSSSX", timezone="IST") on 'eventDate' field it gives the same output.
Java Code for custom Deserilaizer
public class CustomDateDeserializer extends JsonDeserializer<Date>{
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSSXXX");
Date dateTmp = null;
try {
dateTmp = sdf.parse(p.getValueAsString());
} catch (ParseException e) {
e.printStackTrace();
}
return dateTmp;
}
}
If I use @JsonDeserialize annotation annotation above 'eventDate' field as:
@JsonDeserialize(using=CustomDateDeserializer.class)
The output received is:
System.out.println(sampleDatePOJO.getEventDate()); //"Tue Jun 27 10:13:59 IST 2017"
which is correct as the millisecond "573503" part is added to the Date.
I need to understand why my ObjectMapper setDateFormat and @JsonFormat is not working. Or if they are working fine why there is a difference in the output with same SimpeDateFormat format. Any help is greatly appreciated.