Recursive Adapter for Tree

Viewed 32

I have a special use case for gson.
I have the following structure:

public abstract class BaseNode {
    BaseNode left;
    BaseNode right;
}

public class DerivedNode extends BaseNode {
    int val;
}

As you can see this is a binary tree, and I want to apply an adapter for all the nodes in the tree so that I can deserialize them as DerivedNode, not BaseNode, otherwise it will throw unable to instantiate an abstract class. Currently what I do is:

...
Gson gson = new new GsonBuilder().registerTypeAdapter(BaseNode.class, new 
     TypeAdapter<ObjectBasedPermission>() {
        @Override
          public void write(JsonWriter out, ObjectBasedPermission value) throws IOException {}

          @Override
          @SuppressWarnings("ALL")
          public ObjectBasedPermission read(JsonReader in) throws IOException {
            return gson.fromJson(in, DerivedNode);
          }
     }}).create();

My question is can I do this? Is this safe? Will the future update of gson affect this code snippet?

1 Answers

To anyone with same problem, InstanceCreator solves my problem

Related