简体   繁体   中英

Deserialize part of JSON string to DateTime in POJO using Jackson

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?

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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