我有以下 JSON:
{
"type": "cat",
"subType": "flufy",
...
}
我有以下类(class):
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = Cat.class, name = "cat"),
...
})
public abstract class Animal {
public AnimalType type;
public AnimalSubType subType;
public String name;
}
public class Cat extends Animal {
}
public class FlufyAnimal extends Animal {
}
并且我需要在以下条件下反序列化 JSON:
- 如果type
等于cat并且subType
等于flufy必须将JSON反序列化为FlufyAnimal
类,如果type
等于dog有反序列化为 Dog
类。
我该怎么做?
最佳答案
简单来说,它必须看起来像这样:
public class AnimalDesiarializer extends JsonDeserializer<Animal> {
@Override
public Animal deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
String type = node.get("type").asText();
String subType = node.get("subType").asText();
if (Objects.equals(type, "cat") && Objects.equals(subType, "FlufyAnimal")) {
return new Cat(type, subType);
} else {
return new Dog(type, subType);
}
}
}
但是您必须注意,根据您的模型,并非所有 FluffyAnimal
都是猫)
关于java - 如何通过多个属性使用子类型将 JSON 反序列化为类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58916577/