Lets assume that we have the following structure:
class BaseClass {
...
String typeOfSomeClass;
SomeClassBasedOnType someClassBasedOnType;
}
interface SomeClassBasedOnType {
}
class SomeClassBasedOnTypeImpl1 implements SomeClassBasedOnType {
String str1;
}
class SomeClassBasedOnTypeImpl2 implements SomeClassBasedOnType {
String str2;
}
With the above structure I want to store a JSON using Gson. The two possible JSONs that I need to parse are:
{"typeOfSomeClass":"type1", "someClassBasedOnType": {"str1":"someValue"}}
and
{"typeOfSomeClass":"type2", "someClassBasedOnType": {"str2":"someValue"}}
So I created a GsonBuilder and registered InstanceCreator with it. However I can't figure out how to pass the type to the InstanceCreator implementing class, so I can get the concrete implementation based on it. Here is my code atm:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdaptor(SomeClassBasedOnType.class, new SomeClassBasedOnTypeInstanceCreator());
Gson gson = gsonBuilder.create();
BaseClass baseClass = gson.fromJson(strJson, BaseClass.class);
And my InstanceCreator implementation:
class SomeClassBasedOnTypeInstanceCreator implements InstanceCreator<SomeClassBasedOnType> {
public SomeClassBasedOnType(Type type) {
if (the type from BaseClass eq. "type1") {
return new SomeClassBasedOnTypeImpl1()
} else {
return new SomeClassBasedOnTypeImpl2()
}
}
}
The only thing is that I don't know how to get the type from the "base" JSON. Any ideas ?
Just to clarify the "base" JSON contains many keys, which are all the same including the key someClassBasedOnType. The key someClassBasedOnType however may contain two different JSON objects(with different keys) and the way to distinguish those objects is based on the value of the key in the "base" JSON called typeOfSomeClass. I want to get that value in the InstanceCreator of the someClassBasedOnType and use it to return the proper instance of the someClassBasedOnType.