How to handle deserializing with polymorphism?

前端 未结 4 564
既然无缘
既然无缘 2020-11-27 17:04

I have a class like:

public class Barn {
    String type;
    Animal animal;
}

public class Horse extends Animal {
}

public class Cow extends Animal {
}
         


        
4条回答
  •  孤独总比滥情好
    2020-11-27 17:26

    You don't need to write your own Adapter.

    Finally gson has its own RuntimeTypeAdapterFactory to handle java polymorphism but unfortunately it's not part of the gson core library (in order to use it you must copy and paste the class into your project).

    Suppose that you have this Animal.class:

    public class Animal {
        protected String name;
        protected String type;
    
        public Animal(String name, String type) {
            this.name = name;
            this.type = type;
        }
    }
    

    And Horse.class:

    public class Horse extends Animal {
        public Horse(String name) {
            super(name, "horse");
        }
    }
    

    You can initialize the RuntimeTypeAdapterFactory using the code below:

    RuntimeTypeAdapterFactory runtimeTypeAdapterFactory = RuntimeTypeAdapterFactory
    .of(Animal.class, "type")
    .registerSubtype(Horse.class, "horse")
    .registerSubtype(Cow.class, "cow");
    
    Gson gson = new GsonBuilder()
        .registerTypeAdapterFactory(runtimeTypeAdapterFactory)
        .create();
    

    Here you can find a full working example.

提交回复
热议问题