有一个库类,定义是:
class LibraryBean {
public String tag;
public Map<String, Object> attributes;
}
在我的应用程序代码中,我知道 attributes
的每个可能的键map,并且某个key的value的类型是固定的,比如key是"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
}
关于java - 如何反序列化 Map<String, Object> 使用不同类型的不同 key 与 jackson ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33643480/