Jackson deserialize JSON with timestamp field

28,158

I think you need to set the expected date/time format using @JsonFormat annotation as shown below.

class MyObject {
  private Boolean debug;
  @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
  private Timestamp switchTime;
  //...getters, setters, constructors
}

You can also set timezone as @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS",timezone="PST")

Share:
28,158
Kiril  Mytsykov
Author by

Kiril Mytsykov

Updated on July 05, 2022

Comments

  • Kiril  Mytsykov
    Kiril Mytsykov almost 2 years

    I have such string:

    {
       "debug":"false", 
       "switchTime":"2017-04-12 17:04:42.896026"
    }
    

    I'm trying to get object in such approach:

    new ObjectMapper().readValue(string, MyObject.class);
    

    And MyObject class:

    class MyObject {
        private Boolean debug;
        private Timestamp switchTime;
        //...getters, setters, constructors
    }
    

    I have such exception:

    com.fasterxml.jackson.databind.exc.InvalidFormatException: 
    Can not deserialize value of type java.sql.Timestamp from String
    "2017-04-12 17:04:42.896026": not a valid representation (error:
    Failed to parse Date value '2017-04-12 17:04:42.896026': 
    Can not parse date "2017-04-12 17:04:42.896026Z": while it seems 
    to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', 
    parsing fails (leniency? null))  at [Source:   
    {"debug":"false", "switchTime":"2017-04-12 17:04:42.896026"}; 
    

    I don't understand why...If i use in debug mode Timestamp.valueOf() with "2017-04-12 17:04:42.896026" - i have success