[英]How to deserialize JSON having a Date type field to POJO.
I'm working on a REST api using Jersey+Jackson. 我正在使用Jersey + Jackson开发REST api。
I want to convert JSON --> POJO. 我想转换JSON-> POJO。
My Pojo class is having a Date field called 'created' . 我的Pojo班级有一个名为'created'的Date字段 。
In a String 'jsonUser' i have json representation of my Pojo . 在字符串'jsonUser'中,我具有Pojo的 json表示形式。
Now when i use following code to convert JSON representation to Pojo object : 现在,当我使用以下代码将JSON表示形式转换为Pojo对象时:
ObjectMapper mapper = new ObjectMapper();
Pojo oldUser = mapper.readValue(jsonUser, Pojo.class);
I get following error : 我收到以下错误:
Exception: Can not construct instance of java.sql.Timestamp from String value '2013-07-29 11:41:00.0': not a valid representation
Jackson is not able to deserialize String
representation to Date
object. Jackson无法将 String
表示反序列化为 Date
对象。
How can i configure Jackson to do that? 我该如何配置Jackson来做到这一点?
Problem might be in date conversion. 问题可能出在日期转换中。 Just do it in following way: 只需按照以下方式进行:
public class Pojo
{
private String created;
private Date createdDate;
//getter methods.
//setter methods
public void setCreated(String created)
{
this.created = created;
//Logic for converting MySQL-String representation to desired
}
//mapper config
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true );
}
Pojo oldUser = mapper.readValue(jsonUser, Pojo.class);
mapper
which can avoid exception if values are not present. 创建一个mapper
,如果不存在值,则可以避免异常。 created
as String
field and createdDate
with Date
field. 使用created
为String
字段创建POJO并使用Date
字段created
createdDate
。 String to Date
. 在“创建的”设置器中,编写用于将String to Date
转换String to Date
逻辑。 String
to POJO properly by calling setter method on created
. JSON将通过在created
上调用setter方法将String
正确分配给POJO。 string-date conversion
logic will take care of createdDate
field. 在setter中, string-date conversion
逻辑将处理createdDate
字段。 Hope it helps. 希望能帮助到你。
Just store it as long. 只需将其保存很长时间。 To get the long value use dateObj.getTime(); 要获取长值,请使用dateObj.getTime();。 To create a date object from long use new Date(longVal) 要长期创建日期对象,请使用new Date(longVal)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.