Jackson deserialize JSON with timestamp field

我只是一个虾纸丫 提交于 2020-02-29 11:33:50

问题


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


回答1:


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")




回答2:


First of all get timestamp as a string then convert into desired timestamp patter.

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

convert string to desired timestamp format using follweing code

try{
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
    Date parsedDate = dateFormat.parse(switchTime);
    Timestamp timestamp = new java.sql.Timestamp(parsedDate.getTime());
    }catch(Exception e){
    }



回答3:


The value that you see in debug mode is "toString()" version of actual value of timestamp, so don't rely on what you inspect in debug mode. You can use @JsonFormat annotation that helps you to convert your timestamp with specified format. You need to take care of timezones also while converting!



来源:https://stackoverflow.com/questions/43373270/jackson-deserialize-json-with-timestamp-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!