[英]how to write jackson deserializer based on property in json
I want to write json deserializer on class Type so that when Type is deserialized from given json based on name it maps value (of type interface Being) to its current implementation based on some factory method that returns correct class name based on name, and populates remaining class without any explicit deserialization and without creating object of TigerBeing or HumanBeing explicitly using new. 我想在类Type上编写json反序列化器,以便当Type根据名称从给定的json反序列化时,它会根据一些返回基于名称的正确类名称的工厂方法,将值(接口类型为Being)映射到其当前实现,并填充剩余的类,而无需任何显式的反序列化,也无需使用new显式创建TigerBeing或HumanBeing的对象。
I tried to use @jsonCreator but there i have to initialize entire HumanBeing or TigerBeing using new and passing all json in constructor. 我尝试使用@jsonCreator,但我必须使用new初始化整个HumanBeing或TigerBeing并在构造函数中传递所有json。 I need auto mapping for types further used as further pojo can be quite complex.
我需要为进一步使用的类型进行自动映射,因为进一步的pojo可能会非常复杂。
{type:[{
"name": "Human",
"value": {
"height":6,
"weight":100,
"languages":["spanish","english"]
}
},
{
"name":"Tiger",
"value":{
"extinct":1,
"found":["Asia", "America", "Europe", "Africa"]
}
}
]}
I have:
public class Type {
String name;
Being value;
}
public interface Being {
}
public class TigerBeing implements Being {
Integer extinct;
String[] found;
}
public class HumanBeing implement Being {
Integer height;
Integer weight;
String[] languages;
}
import java.io.IOException;
public class BeingDeserializer extends JsonDeserializer<Being> {
@Override
public Expertise deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonMappingException {
JsonNode node = jp.getCodec().readTree(jp);
String beingName = node.get("name").asText();
JsonNode valueNode = node.get("value");
BeingName beingByName = ExpertiseName.getBeingByName(beingName);
if(beingByName ==null) {
throw new JsonMappingException("Invalid Being " + beingName);
}
Being being = JsonUtils.getObjectFromJsonNode(valueNode,
ExpertiseFactory.getExpertise(beingByName).getClass());
return being;
}
}
In this way I was able to solve the above problem. 这样我就可以解决以上问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.