如何反序列化映射<字符串,对象>使用不同的类型与杰克逊不同的键?



有一个库类,定义为:

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);
    }

为已知字段创建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
}

最新更新