1

I'm currently using GSON to parse my JSON to Objects. I was using the standard way like :

Result response= gson.fromJson(reader, Result.class);

Result can be a very complex object with other Complex objects, with up to 5 levels of complex objects. But I have no issues with that. My Question is : I would like to be able to have in some objects an attribute with a flexible type.

For example :

class Class1 {
    String hello;
}

class Class2 {
    String world;
}

class Class3 {
    Class<?> (= class1 or class2) hello;
}

// Parsing time
Class<?> response= gson.fromJson(reader, Class3.class);
try {
    Class1 ret = (Class1)response;
} catch ... {
    Class2 ret = (Class2)response;
}

Hope it's clear enough.

Camille R
  • 1,433
  • 2
  • 17
  • 29

1 Answers1

5

Unfortunately, the latest release of Gson (2.0) still doesn't have built-in support for an easy configuration to provide polymorphic deserialization. So, if Gson must be used (instead of an API that has such built-in support, like Jackson -- using which I've posted complete examples for polymorphic deserialization at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html), then custom deserialization processing is necessary.

For deserialization to polymorphic types, something in the JSON must be present to identify which concrete type to deserialize to.

One approach would be to have an element in the JSON dedicated to just this purpose, where the deserialization code selects the correct type based on the value of the special-purpose element. For example:

{"type":"Class1","hello":"Hi!"} --> deserializes to Class1 instance
{"type":"Class2","world":"Earth"} --> deserializes to Class2 instance

Another approach would be to just switch on the presence of particular JSON element names, though instead of try-catch blocks as demonstrated in the original question, I'd just use if-statements.

See Gson issue 231 for more on this topic, as well as possible information on when a built-in polymorphic deserialization facility might be included in Gson.

Another StackOverflow.com post with an example of polymorphic deserialization with Gson is Polymorphism with gson

Community
  • 1
  • 1
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97