I'm trying to deserialize JSON data into Animal.class and Dog.class which extends Animal.class using custom deserializer. The JSON data below is a simplified one and the real JSON data cannot be deserialized with @JsonSubTypes.
This is how code looks:
- Given JSON data (I can't modify the JSON data format)
[
{
"name": "dog name",
"type": "dog",
"age": 5
},
{
"name": "cat name",
"type": "cat",
"color": "black"
}
]
- Classes
class Animal {
String name;
}
@JsonDeserialize()
class Dog extends Animal {
String name;
int age;
}
- Custom deserializer : deserialize JSON data with
"type": "dog"toDogand all other animals toAnimal.
public class AnimalDeserializer extends StdDeserializer<Animal> {
@Override
public Animal deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
ObjectCodec codec = p.getCodec();
JsonNode node = codec.readTree(p);
JsonNode typeNode = node.get("type");
if (typeNode != null && !typeNode.isNull()) {
String typeText = typeNode.asText();
if (typeText.equals("dog")) {
return codec.treeToValue(node, Dog.class);
}
}
return codec.treeToValue(node, Animal.class);
}
}
It seems like return codec.treeToValue(node, Animal.class); is causing infinite loop. I solved the problem by making Animal.class abstract and creating a new class DefaultAnimal.class, but this way I have to make a lot of redundant default classes.
Please let me know if you have any good ideas.