My problem today is that I have this kind of JSON,
with an array of objects, each object having
two properties: type
and value
.
[{
"type": "Boolean",
"value": false
}, {
"type": "String[]",
"value": ["one", "two", "three"]
}]
As you see, the value
class depends on the type
.
I may have a type: MyClass
, with value
being a complex object.
I want to be able to deserialize this array (and serialize it back into JSON afterwards).
I started looking into the Gson library, but I may change anytime. From what I've read, there is only one way I know of:
public class MyExtractor implements JsonDeserializer<Object> {
@Override
public Object deserialize(JsonElement elem, Type jtype,
JsonDeserializationContext jdc) throws JsonParseException {
// elem is an object
JsonObject obj = elem.getAsJsonObject();
String type = obj.get("type").getAsString();
// Return a different kind of Object depending on the 'type' attr
switch (type) {
case "Boolean":
Boolean bool = obj.get("value").getAsBoolean();
return bool;
case "String[]":
JsonArray data = obj.get("value").getAsJsonArray();
List<String> list = new ArrayList<String>();
for (JsonElement item : data) {
list.add(item.getAsString());
}
return list;
}
}
}
And here I add code to associate each type
to its proper class.
This will probably work as I want, but is there a better way?
This one ends up requiring quite a lot of template.
Also, the deserialized items are cast into Object
so I don't
have access to their methods without reading their getClass()
and
casting them back, and I can't benefit from overloading.
Are there libraries with different approaches to the problem?