Jackson根据属性名称反序列化 [英] Jackson deserialize based on property name
问题描述
我有以下两种类型的JSON对象:
I have the following two types of JSON objects:
{"foo": "String value"}
和
{"bar": "String value"}
它们两者都代表同一基础对象的特殊类型.我如何使用Jackson来反序列化它们?类型信息仅由键本身表示,而不由任何键的值表示(几乎所有示例都使用键的值来确定类型:
Both of them represent a specialized type of the same base object. How can I use Jackson for deserializing them ? The type information is only represented by the keys themselves and not the value for any key (almost all examples use the value of the key for determining the type : https://github.com/FasterXML/jackson-docs/wiki/JacksonPolymorphicDeserialization)
推荐答案
Jackson doesn't offer an out of the box solution for that, but it doesn't mean that you are out of luck.
假设您的类实现一个公共接口或扩展一个公共类,如下所示:
Assuming that your classes implement a common interface or extend a common class, as shown below:
public interface Animal {
}
public class Dog implements Animal {
private String bark;
// Default constructor, getters and setters
}
public class Cat implements Animal {
private String meow;
// Default constructor, getters and setters
}
您可以基于属性名称创建自定义解串器.它允许您定义一个 unique 属性,该属性将用于查找类以对以下内容执行反序列化:
You can create a custom deserializer based on the property name. It allows you to define a unique property that will be used to look up the class to perform the deserialization to:
public class PropertyBasedDeserializer<T> extends StdDeserializer<T> {
private Map<String, Class<? extends T>> deserializationClasses;
public PropertyBasedDeserializer(Class<T> baseClass) {
super(baseClass);
deserializationClasses = new HashMap<String, Class<? extends T>>();
}
public void register(String property, Class<? extends T> deserializationClass) {
deserializationClasses.put(property, deserializationClass);
}
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) p.getCodec();
JsonNode tree = mapper.readTree(p);
Class<? extends T> deserializationClass = findDeserializationClass(tree);
if (deserializationClass == null) {
throw JsonMappingException.from(ctxt,
"No registered unique properties found for polymorphic deserialization");
}
return mapper.treeToValue(tree, deserializationClass);
}
private Class<? extends T> findDeserializationClass(JsonNode tree) {
Iterator<Entry<String, JsonNode>> fields = tree.fields();
Class<? extends T> deserializationClass = null;
while (fields.hasNext()) {
Entry<String, JsonNode> field = fields.next();
String property = field.getKey();
if (deserializationClasses.containsKey(property)) {
deserializationClass = deserializationClasses.get(property);
break;
}
}
return deserializationClass;
}
}
然后实例化并配置反序列化器:
Then instantiate and configure the deserializer:
PropertyBasedDeserializer<Animal> deserializer =
new PropertyBasedDeserializer<>(Animal.class);
deserializer.register("bark", Dog.class); // If "bark" is present, then it's a Dog
deserializer.register("meow", Cat.class); // If "meow" is present, then it's a Cat
将其添加到模块中
SimpleModule module = new SimpleModule("custom-deserializers", Version.unknownVersion());
module.addDeserializer(Animal.class, deserializer);
注册模块并照常执行反序列化:
Register the module and perform the deserialization as usual:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
String json = "[{\"bark\":\"bowwow\"}, {\"bark\":\"woofWoof\"}, {\"meow\":\"meeeOwww\"}]";
List<Animal> animals = mapper.readValue(json, new TypeReference<List<Animal>>() { });
这篇关于Jackson根据属性名称反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!