GSON解析具有相同名称的不同类型数据的JSON

时间:2014-06-04 13:56:51

标签: json deserialization gson

您好我有以下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获得对象和数字?

1 个答案:

答案 0 :(得分:2)

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