I am using jackson mapper to map the json request to an java object directly. To map the date i am using CustomDateSerializer and CustomDateDeSerializer in the getter and setter respectively.
public class CustomJsonDateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String dateString = simpleDateFormat.format(date);
jsonGenerator.writeString(dateString);
}
}
public class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser jsonparser,
DeserializationContext deserializationcontext) throws IOException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String date = jsonparser.getText();
try {
return format.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
my getter and setter in the model
@JsonSerialize(using=CustomJsonDateSerializer.class)
public Date getBirthDate() {
return birthDate;
}
@JsonDeserialize(using = CustomJsonDateDeserializer.class)
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
Exception:
Could not read JSON: java.text.ParseException: Unparseable date: "Fri Sep 12 23:22:46 IST 2014"
Can any one help me fixing this..
The format which you have defined is:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
However it looks like the format which it is expecting is not the same(Fri Sep 12 23:22:46 IST 2014).
It should be like:
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd hh:mm:ss Z yyyy",Locale.ENGLISH);
Check the Oracle docs for SimpleDateFormat