我想在类 Type 上编写 json 反序列化器,以便当 Type 根据名称从给定的 json 反序列化时,它会将值(接口(interface) Being 类型)映射到基于某些工厂方法的当前实现,该工厂方法根据名称返回正确的类名称,并填充剩余的类,无需任何显式反序列化,也无需使用 new 显式创建 TigerBeing 或 HumanBeing 对象。
我尝试使用@jsonCreator,但我必须使用 new 初始化整个 HumanBeing 或 TigerBeing 并在构造函数中传递所有 json 。我需要对进一步使用的类型进行自动映射,因为进一步的 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;
}
}
这样我就能够解决上述问题。
关于java - 如何根据json中的属性编写jackson反序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35455917/