Using Jackson ObjectMapper to serialize the subclass name into JSON, not the superclass

前端 未结 3 2094
执笔经年
执笔经年 2021-02-14 09:58

In the following Jackson/Java code that serializes objects into JSON, I am getting this:

{\"animal\":{\"x\":\"x\"}}

However, what I actually wa

3条回答
  •  感动是毒
    2021-02-14 10:45

    This is the only way I can think of to do it, and it is ugly. Is there a better way?

       @JsonWriteNullProperties(false)
       public static class AnimalContainer
       {
          private Animal animal;
    
          public Animal getCat()
          {
             return animal instanceof Cat ? animal : null;
          }
          public void setCat(Cat cat)
          {
             this.animal = cat;
          }
          public Animal getDog()
          {
             return animal instanceof Dog ? animal : null;
          }
          public void setDog(Dog dog)
          {
             this.animal = dog;
          }
          public Animal getFish()
          {
             return animal instanceof Fish ? animal : null;
          }
          public void setFish(Fish fish)
          {
             this.animal = fish;
          }
       }
    

提交回复
热议问题