JSON nest class data binding

前端 未结 1 1898
广开言路
广开言路 2020-12-10 20:00

{ \"type\":\"cat\", \"animal\":{\"name\":\"cat\"} }

Animal is an abstract class. Cat and Dog are subclass.

Now I am t

相关标签:
1条回答
  • 2020-12-10 20:40

    It's possible, but type in JSON should looks like "type":"com.test.Cat" (fully qualified name)
    Abstract class

    @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="type")
    public abstract class AAnimal 
    {
    }  
    

    subclasses

    public class Cat extends AAnimal
    {
       public String name;
    } 
    public class Dog extends AAnimal
    {
       public String name;
    }  
    

    now, for json

    "{ \"type\":\"com.test.Dog\", \"name\":\"gav-gav\" }"  
    

    it will be Dog instance
    and for

    "{ \"type\":\"com.test.Cat\", \"name\":\"mew-mew\" }" 
    

    it will be Cat instance
    EDIT
    In this case use JsonTypeInfo.As.EXTERNAL_PROPERTY. Example

    public class Container 
    {
       private String type;
    
       private AAnimal animal;
    
       public String getType()
       {
          return type;
       }
    
       public void setType(String type)
       {
          this.type = type;
       }
    
       public AAnimal getAnimal()
       {
          return animal;
       }
    
       @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="type")
       public void setAnimal(AAnimal animal)
       {
          this.animal = animal;
       }
    }  
    

    Animal classes

    public abstract class AAnimal 
    {
       public String name;
    }
    public class Cat extends AAnimal
    {
    }
    public class Dog extends AAnimal
    {
    }  
    

    for

    "{\"type\":\"com.test.Cat\", \"animal\" : {\"name\":\"cat\" }}"
    

    it works well.
    PS. Also you can use use=JsonTypeInfo.Id.MINIMAL_CLASS, in this case you can use only part of fully qualified name
    EDIT2

       @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.EXTERNAL_PROPERTY, property="type")
       @JsonSubTypes({ @Type(value = Cat.class, name = "cat"), @Type(value = Dog.class, name = "dog") })
       public void setAnimal(AAnimal animal)
       {
          this.animal = animal;
       }  
    

    works well for

    "{\"type\":\"cat\", \"animal\" : {\"name\":\"cat\" }}"
    
    0 讨论(0)
提交回复
热议问题