我有一个
private java.sql.Timestamp myDate;
在某些模型 (POJO) 类中。是否可以将它(通过 jackson )转换成类似的东西:
2016 年 11 月 23 日星期三 20:37:09 GMT
?
我知道我可能会使用类似 @JsonProperty
的东西,但是我无法处理这种格式。此外,请记住,我不仅发送 JSON,而且还接收相同的 JSON。
提前致谢!
最佳答案
您可以为时间戳字段添加自定义序列化程序。
public class JsonDateSerializer extends JsonSerializer<Timestamp> {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
@Override
public void serialize(Timestamp arg0, JsonGenerator arg1, SerializerProvider arg2)
throws IOException, JsonProcessingException {
String formattedDate = dateFormat.format(arg0);
arg1.writeString(formattedDate);
}
}
比在 POJO 中的变量上添加 @JsonSerialize,
@JsonSerialize(using = JsonDateSerializer.class)
public Timestamp timestamp;
之后当你像这样序列化它时:
ObjectMapper 映射器 = new ObjectMapper();
mapper.writeValueAsString(//你的对象在这里//);
你会得到这样的东西:
{"timestamp":"Tue, 6 Dec 2016 19:06:33 IST"}
它会将传递的 JSON 反序列化回您的 POJO 中的时间戳字段。
关于java - java.sql.timestamp转Json格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40773848/