用T literal反序列化Json

时间:2017-01-07 10:20:39

标签: java json spring

我收到的json日期格式如下:

yyyy-MM-ddTHH:mm:ssZ

但我无法正确反序化。我试过这样的事情:

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
private SimpleDateFormat createdAt;
杰克逊反序列化者和不同类型的人。没有任何作品。

2 个答案:

答案 0 :(得分:0)

假设您收到了以下JSON;

{"item":{"title":"my title","expires":"2017-01-07T18:46:19Z"}}

<强> Item.java:

@JsonRootName("item")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Item {
 public String title;
 public Date expires;

 @Override
 public String toString() {
    return "Item{" +
       "title='" + title + '\'' +
       ", expires=" + expires +
      '}';
 }
}

使用您要使用的ObjectMapper配置DateFormat

    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"));

    Item t1 = mapper.readValue(jsonString, Item.class);

答案 1 :(得分:0)

尝试将SimpleDateFormat更改为日期

@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ")
private Date createdAt;

TestCase:

    @Test
    public void test() throws Exception{

        ObjectMapper mapper=new ObjectMapper();     
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
        Date date=new Date();       
        TestClass test= new TestClass();
        test.setCreatedAt(date);
        String input=mapper.writeValueAsString(test);   
        TestClass testClass=(TestClass)mapper.readValue(input,TestClass.class);
        System.out.println("testClass"+testClass.toString());
    }

        @JsonRootName("test")
        protected static class TestClass{

            @JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ssZ") 
            private Date createdAt;

       }

回应:

 input:   {"createdAt":"2017-01-07T17:51:03+0000"}
  output :testClass [createdAt=Sat Jan 07 23:21:03 IST 2017]