【问题标题】:JSON serialized object is having date in format 2006-10-04T19:49:49. Not able to deserialized itJSON 序列化对象的日期格式为 2006-10-04T19:49:49。无法反序列化它
【发布时间】:2017-01-02 07:52:47
【问题描述】:

我正在使用 struts2 并序列化对象并将其传递给 JSP。从 jsp 我再次将此对象传递给 java 并尝试使用以下代码对其进行反序列化

ObjectMapper objectMapper=new ObjectMapper();
receiptDocument = objectMapper.readValue(receiptDocumentStr,new TypeReference<ReceiptDocument>(){});

被序列化的对象在时间戳中有一个属性。因此,当其序列化时,日期将转换为以下格式 2006-10-04T19:49:49。但是当我尝试反序列化它时,它会给出异常

org.codehaus.jackson.map.JsonMappingException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

请建议我应该如何对其进行反序列化。

【问题讨论】:

    标签: java json jackson deserialization


    【解决方案1】:

    尝试按照here的描述使用

      objectMapper.setDateFormat(myDateFormat);
    

    【讨论】:

      【解决方案2】:

      我试图对 JSON 对象进行反序列化,该对象通过以下代码使用 struts2 发送到 jsp

      @Result(name = SUCCESS, type = JSON, params = {
      "ignoreHierarchy", "false", "includeProperties","bookList\\[\\d+\\]\\..*})
      

      但是当我使用jquery post 将此 bookList 发送到服务器并尝试反序列化它时,它不起作用。所以我按照以下方式对其进行了序列化

      SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      ObjectMapper mapper = new ObjectMapper();
      mapper.getSerializationConfig().setDateFormat(sd);
      bookListJsonString=  mapper.writeValueAsString(bookList);
      

      反序列化代码如下

      ObjectMapper objectMapper=new ObjectMapper();
      SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      objectMapper.getDeserializationConfig().setDateFormat(sd);
      objectMapper.getDeserializationConfig().disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES); //To avoid failure if there is no any class fields.                
      List<BooksDocument> bookList =  objectMapper.readValue(bookListJsonString, new TypeReference<List<BooksDocument>>() {});
      

      如果有人有更好的方法。请张贴。

      【讨论】:

        猜你喜欢
        • 2011-08-14
        • 2016-12-30
        • 2016-10-08
        • 2014-08-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多