将JSON字符串中的部分内容反序列化为POJO中的DateTime,使用Jackson库。

huangapple go评论133阅读模式
英文:

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

https://www.baeldung.com/jackson-serialize-dates

答案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
}

huangapple
  • 本文由 发表于 2020年9月22日 10:53:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/64002427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定