有一个特征和一个注释完全符合这个目的。
我测试过,它适用于UUID,如您的示例所示:
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);
还有更常见的类型,如字符串工作:
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);
}
}
(我首先在这篇博客文章中发现了此功能)。