Reputation: 797
Im using GSON on an Android device.
I have JSON data coming in, but it can come in the form of a few different objects.
This is how I think I need to handle it.
public class Command
{
public String Command;
}
String json = {"Command":"Something", "date":"now"}
String command = gson.fromJson(message, Command.class);
Then switch on command
Switch(command)
{
case: something
//deserialize to "something" object;
break;
case: other somthing
//deserialize to "other somthing" object;
break;
case: object 3
//deserialize to "object 3" object;
break;
}
Does GSON have some sort of Auto Mapping to the best suited object, so i dont have to make a custom object handler and deseraialize the String twice?
Upvotes: 3
Views: 1833
Reputation: 421
I would parse it as a general JsonObject using
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(json).getAsJsonObject();
then find something unique about each json schema and then depending on which schema convert it to a bean using
gson.fromJson(jsonObject, AppropriateBean.class);
Upvotes: 1
Reputation: 21184
I think an example of what you are trying to achieve is covered in the user guide. See the part about Serializing and Deserializing Collection with Objects of Arbitrary Types. They recommend to use the underlying parser API and then the fromGson
method onward, so you don't have to parse intermediary objects, which sounds like a good approach to me. But the also provide two alternatives that you might try.
Upvotes: 0