我有以下JSON:
{
"type": "cat",
"subType": "flufy",
...
}我有以下课程:
@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类。我该怎么做呢?
发布于 2019-11-18 15:26:58
简单地说,它必须是这样的:
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都是猫)
https://stackoverflow.com/questions/58916577
复制相似问题