【问题标题】:Deserialize part of JSON string to DateTime in POJO using Jackson使用 Jackson 将部分 JSON 字符串反序列化为 POJO 中的 DateTime
【发布时间】:2021-01-08 03:33:06
【问题描述】:

我正在读取给定表单的 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?

【问题讨论】:

标签: java datetime jackson deserialization pojo


【解决方案1】:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    猜你喜欢
    • 2012-04-07
    • 2013-01-08
    • 1970-01-01
    • 2014-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-08
    • 2020-12-10
    相关资源
    最近更新 更多