3

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?

4

2 回答 2

1

我会将其解析为一般 JsonObject 使用

    JsonParser parser = new JsonParser();
    JsonObject jsonObject = parser.parse(json).getAsJsonObject();

然后找到每个 json 模式的独特之处,然后根据哪个模式将其转换为 bean

    gson.fromJson(jsonObject, AppropriateBean.class);
于 2013-09-03T20:50:32.513 回答
0

我认为用户指南中涵盖了您要实现的目标的示例。请参阅有关使用任意类型的对象对集合进行序列化和反序列化的部分。他们建议先使用底层解析器 API,然后再使用fromGson方法,这样您就不必解析中间对象,这对我来说听起来是个好方法。但也提供了两种可供您尝试的替代方案。

于 2013-09-03T20:36:58.453 回答