Deserializing an abstract class in Gson

前端 未结 4 1988
盖世英雄少女心
盖世英雄少女心 2020-11-27 16:10

I have a tree object in JSON format I\'m trying to deserialize with Gson. Each node contains its child nodes as fields of object type Node. Node is an interface, which has

4条回答
  •  余生分开走
    2020-11-27 16:48

    I'd suggest adding a custom JsonDeserializer for Nodes:

    Gson gson = new GsonBuilder()
        .registerTypeAdapter(Node.class, new NodeDeserializer())
        .create();
    

    You will be able to access the JsonElement representing the node in the deserializer's method, convert that to a JsonObject, and retrieve the field that specifies the type. You can then create an instance of the correct type of Node based on that.

提交回复
热议问题