I have a class hierarchy that I want to convert to and from GSON. I'm not sure how to approach this with GSON (I currently have a Factory
class that looks at the JSONObject and based on presence or absence of keys it calls the right constructor, which in turn delegates some of its work to the super class). When I store these objects in the local SQLite DB, I use an integer to denote their type and the factory class uses this type to call the right constructor. I don't have this type in the JSON (which isn't mine).
How do I tell GSON based on the contents of the JSON object which type of object to instantiate for me?
In the examples below, treat ...
inside the JSON brackets as there may or may not be more elements
Here's a breakdown of the class hierarchy:
There is a base abstract type: SuperType
with a JSON representation {"ct":12345,"id":"abc123 ...}
There are 2 main abstract sub types: TypeA
(has json key "a") and TypeB
(has json key "b")
TypeA
Example: {"ct":12345,"id":"abc123, "a":{...}}
TypeA
has 15 children (Let's call these TypeA_A
to TypeA_P
). The JSON representation of these objects would be something like {"ct":12345,"id":"abc123, "a":{"aa":1 ...} ...}
or {"ct":12345,"id":"abc123, "a":{"ag":"Yo dawg I head you like JSON" ...} ...}
TypeB
Example: {"ct":12345,"id":"abc123, "b":{...} ...}
TypeB
has another abstract subtype (TypeB_A
) and few children (Let's call these TypeB_B
to TypeB_I
). The JSON representation of these objects would be {"ct":12345,"id":"abc123, "b":{"ba":{...} ...} ...}
or {"ct":12345,"id":"abc123, "b":{"bg":"Stayin alive" ...} ...}
I could throw it all in one monster type and treat each of the sub types as an inner object, but I'll end up with a lot of inner members that are null (sort of like a tree with a lot of branches that lead to nowhere). As a result, I'll end up with a lot of if (something==null)
just to determine which one of these types I'm dealing with.
I've looked at TypeAdapter
and TypeAdapterFactory
, but I'm still not sure how to approach this since I have to look at the content of the incoming JSON.
How do I tell GSON based on the contents of the JSON object which type of object to instantiate for me?
Thanks.