根据字段值用 GSON 解析 JSON(与改造一起使用)

Parse JSON with GSON based on filed value (used with retrofit)

我有两个具有相似字段的 JSON 对象。唯一的区别是第一个总是有 field

type: "type1"

第二个可以在 'type' 字段中包含除 'type1' 之外的任何内容。

我希望将它们解析为具有不同 类 的 java 个对象(使用 类 FirstType.class 和 OtherType.class)。可能吗?

对象一:

{
    id: "1j23jr8swgs8"
    type: "type1"
}

对象二:

{
    id: "3sdaa3dq18"
    type: "unknown_type"
}

和java 类:

class FirstType
{
    String id;
}    

class OtherType
{
    String id;
}

好久没用 Gson 了,不过应该是这样的:

//convert your json string into a json object
JsonElement element = new JsonParser().parse(jsonString);
JsonObject  object = element.getAsJsonObject();

//get the relevant value from your object
String result = object.get("type").toString();

//compare and convert accordingly
if (result.equals("type1")) {
    ObjectOne object = gson.fromJson(element, ObjectOne.class);
} else {
    ObjectTwo object = gson.fromJson(element, ObjectTwo.class);
}

试试这个,看看它是否有效!

Google gson 在这里可以很好地工作。

你可以这样做:-

class ObjectName {
String id;
String type;
}

Gson gson = new GsonBuilder().serializeNulls().create();
ObjectName name = gson.fromJson(json, ObjectName.class);

FirstType firstType = null;
SecondType secondType = null;
if(name.type.equals("type1"))
firstType = new FirstType(name.id);
else
secondType = new SecondType(name.id);