views:

50

answers:

1

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 several concrete class implementations. During the deserialization process, how can I communicate to Gson which concrete class to implement when deserializing the node, if I do not know a priori which type the node belongs to? Each Node has a member field specifying the type. Is there a way to access the field when the object is in serialized form, and somehow communicate the type to Gson?

Thanks!

A: 

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.

ColinD
That worked perfectly. Thanks!
@eng-carlin It's customary to upvote and accept an answer if it works for you, so if you could do that I'd appreciate it.
ColinD
The green check mark has been clicked. I'd upvote you, but my reputation isn't high enough :(