Java – Jackson deserializes JSON with timestamp fields
•
Java
I have this string:
{
"debug":"false","switchTime":"2017-04-12 17:04:42.896026"
}
I try to get objects in this way:
new ObjectMapper().readValue(string,MyObject.class);
And MyObject classes:
class MyObject {
private Boolean debug;
private Timestamp switchTime;
//...getters,setters,constructors
}
I have this exception:
com.fasterxml.jackson.databind.exc.InvalidFormatException:
Can not deserialize value of type java.sql.Timestamp from String
"2017-04-12 17:04:42.896026": not a valid representation (error:
Failed to parse Date value '2017-04-12 17:04:42.896026':
Can not parse date "2017-04-12 17:04:42.896026Z": while it seems
to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'',parsing fails (leniency? null)) at [Source:
{"debug":"false","switchTime":"2017-04-12 17:04:42.896026"};
I don't understand why... If I use timestamp in debug mode Valueof () and "2017-04-12 17:04:42.896026" – I have succeeded
Solution
I think you need to use the @ jsonformat annotation to set the expected date / time format, as shown below
class MyObject {
private Boolean debug;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
private Timestamp switchTime;
//...getters,constructors
}
You can also set the time zone to @ jsonformat (pattern = "yyyy MM DD HH: mm: SS. SSS", timezone = "PST")
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
