繁体   English   中英

使用 Jackson 将 JSON 字符串的一部分反序列化为 POJO 中的 DateTime

[英]Deserialize part of JSON string to DateTime in POJO using Jackson

我正在读取给定形式的 json 并将其存储为 POJO。

{
 "details" : [ 
   {
    "version" : 1, 
    "time" : "2021-01-01T00:00:00.000Z",
   }
 ]
}

我的 POJO class 看起来像:

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?

应该能够为您的日期使用@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

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

添加这个对我有用。 在 POJO 中,将时间指定为“DateTime”而不是“String”。

public class Details
{
    private int version;
    private DateTime time;
    ...
    //getters & setters
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM