我正在使用 Jersey+Jackson 开发 REST API。
我想转换 JSON --> POJO。
我的Pojo类有一个名为'created'的日期字段。
在字符串'jsonUser'中,我有我的Pojo的json表示。
现在,当我使用以下代码将 JSON 表示转换为 Pojo 对象时:
ObjectMapper mapper = new ObjectMapper();
Pojo oldUser = mapper.readValue(jsonUser, Pojo.class);
我收到以下错误:
Exception: Can not construct instance of java.sql.Timestamp from String value '2013-07-29 11:41:00.0': not a valid representation
Jackson 无法将String
表示形式反序列化为Date
对象。
我如何配置 Jackson 来做到这一点?
最佳答案
问题可能出在日期转换上。 只需按照以下方式进行即可:
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);
- 创建一个
映射器
,它可以避免值不存在时出现异常。 - 使用
created
作为String
字段和createdDate
创建 POJO日期
字段。 - 在“created”的 setter 中,编写用于将
字符串转换为日期
的逻辑。 - JSON 将通过调用
created
上的 setter 方法正确地将String
分配给 POJO。 - 在 setter 中,
字符串-日期转换
逻辑将处理createdDate
字段。
希望有帮助。
关于java - 如何将具有日期类型字段的 JSON 反序列化为 POJO。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918174/