杰克逊 java.util.Date 值在 Map<String, Object>(反)序列化

Ste*_*ich 6 java jackson jackson-databind

考虑这个属性

@JsonProperty
private Map<String, Object> myMap;
Run Code Online (Sandbox Code Playgroud)

当一个包含的java.util.Date值被序列化时,它不会被Date再次反序列化,因为类型信息不存在于Map<String, Object>. 我怎样才能绕过这个问题?我阅读了有关此问题的答案,将是一个解决方法,但无法区分包含日期的字符串和在地图中序列化为字符串的日期。我可以告诉 Jackson 为每个映射值包含类型信息,以便 Jackson 可以正确反序列化它们吗?

die*_*ter 5

实现自定义反序列化器并将注释添加@JsonDeserialize(using = DateDeserializer.class)到您的字段。

看一下这个例子:

你的 Json-Bean

public class Foo {

    private String            name;

    @JsonProperty
    @JsonDeserialize(using = DateDeserializer.class)
    private Map<String, Object> dates;

    [...] // getter, setter, equals, hashcode
}
Run Code Online (Sandbox Code Playgroud)

解串器

public class DateDeserializer extends JsonDeserializer<Map<String, Object>> {

    private TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {};

    @Override
    public Map<String, Object> deserialize(JsonParser p, DeserializationContext ctxt, Map<String, Object> target) throws IOException, JsonProcessingException {

        Map<String, Long> map = new ObjectMapper().readValue(p, typeRef);

        for(Entry<String, Long> e : map.entrySet()){

            Long value = e.getValue();
            String key = e.getKey();

            if(value instanceof Long){ // or if("date".equals(key)) ...
                target.put(key, new Date(value));
            } else {
                target.put(key, value); // leave as is
            }

        }

        return target;
    }

    @Override
    public Map<String, Object> deserialize(JsonParser paramJsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return this.deserialize(paramJsonParser, ctxt, new HashMap<>());
    }

}
Run Code Online (Sandbox Code Playgroud)

简单测试

public static void main(String[] args) throws Exception {

    Foo foo1 = new Foo();
    foo1.setName("foo");
    foo1.setData(new HashMap<String, Object>(){{
        put("date",   new Date());
        put("bool",   true);
        put("string", "yeah");
    }});
    ObjectMapper mapper = new ObjectMapper();
    String jsonStr = mapper.writeValueAsString(foo1);
    System.out.println(jsonStr);
    Foo foo2 = mapper.readValue(jsonStr, Foo.class);

    System.out.println(foo2.equals(foo1));

}
Run Code Online (Sandbox Code Playgroud)