Java Jackson 使用时间戳字段反序列化 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43373270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson deserialize JSON with timestamp field
提问by Kiril Mytsykov
I have such string:
我有这样的字符串:
{
"debug":"false",
"switchTime":"2017-04-12 17:04:42.896026"
}
I'm trying to get object in such approach:
我正在尝试以这种方法获取对象:
new ObjectMapper().readValue(string, MyObject.class);
And MyObject class:
和 MyObject 类:
class MyObject {
private Boolean debug;
private Timestamp switchTime;
//...getters, setters, constructors
}
I have such exception:
我有这样的例外:
com.fasterxml.Hymanson.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 in debug mode Timestamp.valueOf() with "2017-04-12 17:04:42.896026" - i have success
我不明白为什么......如果我在调试模式下使用 Timestamp.valueOf() 和 "2017-04-12 17:04:42.896026" - 我成功了
采纳答案by Justin Jose
I think you need to set the expected date/time format using @JsonFormat
annotation as shown below.
我认为您需要使用@JsonFormat
注释设置预期的日期/时间格式,如下所示。
class MyObject {
private Boolean debug;
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
private Timestamp switchTime;
//...getters, setters, constructors
}
You can also set timezone as @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS",timezone="PST")
您还可以将时区设置为 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS",timezone="PST")
回答by adi
The value that you see in debug mode is "toString()" version of actual value of timestamp, so don't rely on what you inspect in debug mode. You can use @JsonFormat annotation that helps you to convert your timestamp with specified format. You need to take care of timezones also while converting!
您在调试模式下看到的值是时间戳实际值的“toString()”版本,因此不要依赖您在调试模式下检查的内容。您可以使用 @JsonFormat 注释来帮助您将时间戳转换为指定格式。您在转换时也需要注意时区!
回答by firstpostcommenter
I faced the similar problem when I was using lombok in the POJO class which has @Builder
and @Value
annotations
我遇到类似的问题时,我是用在龙目岛拥有POJO类@Builder
和@Value
注解
I have also added the annotation AllArgsConstructor
and then it is working fine with my custom deserializer code
我还添加了注释AllArgsConstructor
,然后它与我的自定义解串器代码一起工作正常