gpt4 book ai didi

java - 如何基于 json 中的属性编写 jackson 反序列化器

转载 作者:行者123 更新时间:2023-11-30 10:49:23 24 4
gpt4 key购买 nike

我想在类 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com