如何使用jackson的不同密钥使用不同类型的Map <string,object =“”>反序列化?

时间:2015-11-11 02:50:36

标签: java json jackson

有一个库类,定义是:

class LibraryBean {
    public String tag;
    public Map<String, Object> attributes;
}

在我的应用程序代码中,我知道attributes映射的每个可能的键,并且某个键的值的类型是固定的,例如,如果键是"location",那么值类型是Location,如果密钥为"timestamp",则值类型为Long。将ArrayList<LibraryBean>写入json字符串很简单,但是如何反序列化json字符串以使值恢复其类型?

public void test(ArrayList<LibraryBean> sampleList) { 
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeAsString(sampleList);

        List<LibraryBean> recovered = mapper.readValue(jsonString); // what should I do here?

        // I'm sure sampleList.get(0).attributes.get("location") != null
        AssertTrue(sampleList.get(0).attributes.get("location") instanceof Location);
    }

1 个答案:

答案 0 :(得分:2)

为已知字段创建您的pojo:

class Attributes {
    private Location location;
    ...
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    ... getters and setters

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

}

class LibraryBean {
    private String tag;
    private Attributes attributes;

    ... getters and setters
}