-1

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?

Tisha
  • 61
  • 1
  • 2
  • 11
  • Have you tried googling or searching online before posting this question? A simple search online will give you the results. https://www.logicbig.com/tutorials/misc/jackson/json-format.html – Adithya Upadhya Sep 22 '20 at 03:02
  • This works with Date, not DateTime. – Tisha Sep 22 '20 at 04:48
  • 1
    Take a look at [Spring Boot Jackson date and timestamp Format](https://stackoverflow.com/questions/55256567/spring-boot-jackson-date-and-timestamp-format/55270120#55270120) – Michał Ziober Sep 22 '20 at 06:56

2 Answers2

0

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

locus2k
  • 2,802
  • 1
  • 14
  • 21
  • It needs to be Joda time, 'DateTime' instead of Date because I am later checking it with another DateTime. I had tried the 8th step in this link. I am getting the error 'Incompatible types. Found , required: 'java.lang.Class extends com.fasterxml.Jackson.databind.JsonSerializer' – Tisha Sep 22 '20 at 05:17
  • Can you post what you've tried and any stacktraces that you received. Will be helpful – locus2k Sep 22 '20 at 12:23
  • @lakshmisubhash, Take a look at [Serializing Joda DateTime object is creating different output depending on context](https://stackoverflow.com/questions/57824754/serializing-joda-datetime-object-is-creating-different-output-depending-on-conte/57828928#57828928), [How to deserialize Joda DateTime using Jackson with Jersey 2 Client in Spring MVC?](https://stackoverflow.com/questions/25404703/how-to-deserialize-joda-datetime-using-jackson-with-jersey-2-client-in-spring-mv/25413677#25413677) – Michał Ziober Sep 22 '20 at 13:01
-1
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
}
Tisha
  • 61
  • 1
  • 2
  • 11