您好,我有以下 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
有时保存一个数字,有时保存一个对象。如何获取端口
来获取对象和数字?
最佳答案
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());
关于json - GSON解析同名下具有不同类型数据的JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24039438/