0

I use jackson to deserialize an java object LivingBeing which has Animal class in it. So far I was dierctly passing object of Animal.

class LivingBeing {
@JsonProperty('animal')
Animal animal;
}
class Animal {
@JsonProperty('color')
String color;
}

But now, we have extended Animal class with classes Cat, Dog.

class Cat extends Animal {
@JsonProperty('cat_specific_feature')
String catFeature;
}
class Dog extends Animal {
@JsonProperty('dog_specific_feature')
String dogFeature;
@JsonProperty('dog_special_power')
String dogPower;
}

Example jsons:

livingbeing: {animal :{color :”black”}}

livingbeing: {animal :{color :”black”, cat_specific_feature :”someCatFeature”}}

livingbeing: {animal :{color :”black”, dog_specific_feature :”someDogFeature”, dog_special_power:”power”}}

I do not already know what kind of object will be coming to living being. My only idea is to use some extra flag in LivingBeing like flag: Cat,Dog etc as enum, but dont feel its a good design. Currently, if(livingbeing.getanimal() instanceOf Cat) is false because livingbeing knows only Animal type. Note: Cat and Dog are representing diff use cases. And I can't put 'feature' in Animal. This is only an example code structure that represents different use cases . Constructor overloading for Animal is not possible due to function erasure. How can I deserialize the LivingBeing?

drk
  • 153
  • 1
  • 17
  • 1
    See the [second answer](https://stackoverflow.com/a/50013090) from the linked question, especially the update in there. – Tom Mar 22 '21 at 10:06
  • thats a really good hint of both JsonTypeInfo and aliter, thanks a lot! – drk Mar 22 '21 at 12:56

1 Answers1

0

There are several ways you can do it.

  1. Using JsonNode
  2. Using map
  3. Using @JsonAnySetter
  4. Creating a Custom Deserializer

Details here

For your case creating a custom Deserializer will be a better choice.

Custom Deserializer:

public class DogDeserializer extends StdDeserializer<Item> { 

    public DogDeserializer() { 
        this(null); 
    } 

    public DogDeserializer(Class<?> vc) { 
        super(vc); 
    }

    @Override
    public Dog deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        JsonNode node = jp.getCodec().readTree(jp);
        String dogFeature = node.get("dogFeature").asText();
        String dogPower = node.get("dogPower").asText();
      

        return new Dog(dogFeature,dogPower);
    }
}
@JsonDeserialize(using = DogDeserializer.class)
class Dog extends Animal{
}

Details here

aang13
  • 389
  • 1
  • 3
  • 14