【问题标题】:GSON to parse JSON having different type data under same nameGSON 解析具有相同名称的不同类型数据的 JSON
【发布时间】:2014-06-04 13:56:51
【问题描述】:

您好,我有以下 json 数据

{
  "actionslist": [
    {
      "type": "SET_TP_DST",
      "port": 135
    },
    {
      "type": "OUTPUT",
      "port": {
        "node": {
          "id": "00:00:00:00:00:00:00:03",
          "type": "OF"
        },
        "id": "2",
        "type": "OF"
      }
    }
  ]
}

我想使用gson.fromJson 反序列化这个 json。但这里的问题是port 有时包含一个数字,有时包含一个对象。如何获取port 来获取对象和数字?

【问题讨论】:

  • 这取决于type ?你可以编写自己的反序列化器

标签: json deserialization gson


【解决方案1】:
public class PortConverter implements JsonDeserializer<Port> {
    public Port deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx) {
        Port port = null;
        if (json.isJsonPrimitive()) {
            // handle your first case:
            port = new Port(json.getAsInt());
            // in this case you will have a Port object with populated id
        } else if (json.isJsonObject()) {
            // manually parse your Port object
            port = new Port();
            port.setNode(ctx.deserialize(json.getAsJsonObject().get("node"), Node.class));
            port.setId(json.getAsJsonObject().get("id").getAsInt());
            port.setType(json.getAsJsonObject().get("type").getAsString());
        }
        return port;
    }
}

POJO 类:

class Port {
    int id;
    String type;
    Node node;

    Port() { }

    Port(int id) { this.id = id; }

    /* setters */

    class Node {
        String id;
        String type;
    }
}

class Action {
    String type;
    Port port;
}

注册你的反序列化器:

gsonBuilder.registerTypeAdapter(Port.class, new PortConverter());

【讨论】:

  • 不错的答案,但the documenation 说“新应用程序应该更喜欢TypeAdapter,它的流式API 比这个接口的树形API 更高效。”
猜你喜欢
  • 1970-01-01
  • 2017-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多