问题描述
我希望将 JSON 对象中的任何未知字段反序列化为 Map
中的条目,Map
是 POJO 的成员.
I'm looking to deserialize any unknown fields in a JSON object as entries in a Map
which is a member of a POJO.
例如,这里是 JSON:
For example, here is the JSON:
{
"knownField" : 5,
"unknownField1" : "926f7c2f-1ae2-426b-9f36-4ba042334b68",
"unknownField2" : "ed51e59d-a551-4cdc-be69-7d337162b691"
}
这是 POJO:
class MyObject {
int knownField;
Map<String, UUID> unknownFields;
// getters/setters whatever
}
有没有办法用 Jackson 配置它?如果没有,是否有一种有效的方法来编写 StdDeserializer
来完成它(假设 unknownFields
中的值可以是更复杂但众所周知的一致类型)?
Is there a way to configure this with Jackson? If not, is there an effective way to write a StdDeserializer
to do it (assume the values in unknownFields
can be a more complex but well known consistent type)?
推荐答案
有一个特性和注释正好符合这个目的.
There is a feature and an annotation exactly fitting this purpose.
我进行了测试,它可以与您的示例中的 UUID 一起使用:
I tested and it works with UUIDs like in your example:
class MyUUIDClass {
public int knownField;
Map<String, UUID> unknownFields = new HashMap<>();
// Capture all other fields that Jackson do not match other members
@JsonAnyGetter
public Map<String, UUID> otherFields() {
return unknownFields;
}
@JsonAnySetter
public void setOtherField(String name, UUID value) {
unknownFields.put(name, value);
}
}
它会像这样工作:
MyUUIDClass deserialized = objectMapper.readValue("{" +
""knownField": 1," +
""foo": "9cfc64e0-9fed-492e-a7a1-ed2350debd95"" +
"}", MyUUIDClass.class);
还有更常见的类型,比如字符串:
Also more common types like Strings work:
class MyClass {
public int knownField;
Map<String, String> unknownFields = new HashMap<>();
// Capture all other fields that Jackson do not match other members
@JsonAnyGetter
public Map<String, String> otherFields() {
return unknownFields;
}
@JsonAnySetter
public void setOtherField(String name, String value) {
unknownFields.put(name, value);
}
}
这篇关于Jackson 将额外的字段反序列化为 Map的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!