user3156850 user3156850 - 1 year ago 74
Android Question

Parse list of dynamic classes in gson android

I have a collection of classes, such as this:

entityClasses = new HashMap<String, Class>();
entityClasses.put("EntityType1", EntityType1.class);
entityClasses.put("EntityType2", EntityType2.class);

I also have a JSON list of their instances as well:

String entityJSON = "[{"type":"EntityType1","name":"... attributes"},...]";

Where the type attribute will determine the class of the object that will be the target of JSON parsing. How can I parse these using gson?

I tried with the following:

String type = "EntityType1"; // I already can fetch this.
final Class entityClass = entityClasses.get(type);
new Gson().fromJson(entityJSON, new TypeToken<ArrayList<entityClass>>(){}.getType());

Which would work if entityClass was an actual class name, and not a variable that represents a class. In my case however, I get the following error:
Unknown class: 'entityClass'

So how is it possible to parse by a Class variable?

Thanks in advance!

Answer Source

In general, you can't do that since you should pass a class as a generic type: not List<String.class>, but List<String>.

But you can use a workaround like this: store list TypeToken's instead of list generic types:

entityClasses = new HashMap<String, TypeToken>();
entityClasses.put("EntityType1", new TypeToken<ArrayList<EntityType1>>(){});

String type = "EntityType1"; // I already can fetch this.
final TypeToken typeToken= entityClasses.get(type);
new Gson().fromJson(entityJSON, typeToken.getType());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download