英文:
Deserialize part of JSON string to DateTime in POJO using Jackson
问题
我正在阅读给定形式的 JSON 并将其存储为 POJO。
{
"details" : [
{
"version" : 1,
"time" : "2021-01-01T00:00:00.000Z"
}
]
}
我的 POJO 类如下:
public class Details
{
private int version;
private String time;
public Integer getVersion(){
return version;
}
public void setVersion(int version){
this.version = version;
}
public String getTime(){
return time;
}
public void setTime(String time){
this.time = time;
}
}
时间被读取为字符串。如何使用 Jackson 反序列化为 DateTime?
英文:
I am reading a json of the given form and storing it as a POJO.
{
"details" : [
{
"version" : 1,
"time" : "2021-01-01T00:00:00.000Z",
}
]
}
My POJO class looks like :
public class Details
{
private int version;
private String time;
public Integer getVersion(){
return version;
}
public void setVersion(int version){
this.version = version;
}
public String getTime(){
return time;
}
public void setTime(String time){
this.time = time;
}
}
The time is being read as a string. How do I deserialize it to DateTime using Jackson?
答案1
得分: 0
能够使用 @JsonFormat
注解来处理日期。首先,将您的时间字段从 String
更改为 Date
,然后进行以下操作:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'hh:mm:ss.SSS'Z'")
private Date time;
以下链接展示了如何进行其他不同的转换,特别是针对标准时间格式:
https://www.baeldung.com/jackson-serialize-dates
英文:
Should be able to use @JsonFormat
annotation for your date. First change your time field from String
to Date
then do the following:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy'T'hh:mm:ss.SSS'Z'")
private Date time;
The following link shows how to do other different conversions especially if its a standard time format
答案2
得分: -1
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
对我而言,加入这段代码有效。
在POJO中,将时间设置为 'DateTime' 而不是 'String'。
public class Details
{
private int version;
private DateTime time;
...
// 获取器与设置器
}
英文:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
Adding this worked for me.
In POJO, gave time as 'DateTime' instead of 'String'.
public class Details
{
private int version;
private DateTime time;
...
//getters & setters
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论