JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)
Annotate your created_date
field with the JsonFormat
annotation to specify the output format.
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = TimeZone.getDefault(), locale = Locale.getDefault())
Note that you may need to pass in a different Locale and TimeZone if they should be based on something other than what the server uses.
You can find out more information in the docs.
I have the same problem, so I write a custom date deserializationwith @JsonDeserialize(using=CustomerDateAndTimeDeserialize.class)
public class CustomerDateAndTimeDeserialize extends JsonDeserializer<Date> { private SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); @Override public Date deserialize(JsonParser paramJsonParser, DeserializationContext paramDeserializationContext) throws IOException, JsonProcessingException { String str = paramJsonParser.getText().trim(); try { return dateFormat.parse(str); } catch (ParseException e) { // Handle exception here } return paramDeserializationContext.parseDate(str); }}
- If you want to bind a
JSON
string to date, this process is calleddeserialization
, notserialization
. To bind a
JSON
string to date, create a custom date deserialization, annotatecreated_date
or its setter with@JsonDeserialize(using=YourCustomDateDeserializer.class)
where you have to implement the method public Date deserialize(...)
to tell Jackson how to convert a string to a date.
Enjoy.