【问题标题】:Parse JSON with GSON based on filed value (used with retrofit)基于字段值使用 GSON 解析 JSON(与改造一起使用)
【发布时间】:2015-03-23 07:47:25
【问题描述】:

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

type: "type1"

并且 second 可以在 '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;
}

【问题讨论】:

  • 你能发布完整的 json 吗?
  • 我们需要更多解释来帮助您。
  • 当然可以,但具体代码取决于你的json结构。

标签: java android json gson retrofit


【解决方案1】:

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);

【讨论】:

    【解决方案2】:

    我已经很久没有使用 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);
    }
    

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

    【讨论】:

      猜你喜欢
      • 2016-02-25
      • 1970-01-01
      • 2018-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2017-02-28
      • 2016-08-23
      相关资源
      最近更新 更多