GSON用相同的名称解析具有不同类型数据的JSON [英] GSON to parse JSON having different type data under same name
本文介绍了GSON用相同的名称解析具有不同类型数据的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我有以下json数据
{
actionslist:[
{
type:SET_TP_DST,
port:135
},
{
type:OUTPUT,
端口:{
节点:{
id:00:00:00:00:00:00:03,
type:OF
},
id:2,
type:OF
}
}
]
}
我想用 gson.fromJson
。但是这里的问题是 port
有时会保存一个数字,有时候会保存一个对象。我怎样才能得到 port
来获取对象和数字?
public class PortConverter实现了JsonDeserializer< Port> {
public Port反序列化(JsonElement json,Type typeOfT,JsonDeserializationContext ctx){
Port port = null;
if(json.isJsonPrimitive()){
//处理您的第一种情况:
port = new Port(json.getAsInt());
//在这种情况下,您将拥有一个带有填充ID
的Port对象else if(json.isJsonObject()){
//手动解析您的Port对象
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());
}
返回端口;
$ / code $ / pre
POJO类别:
class Port {
int id;
字符串类型;
节点节点;
Port(){}
Port(int id){this.id = id; }
/ * setters * /
class Node {
String id;
字符串类型;
}
}
类动作{
字符串类型;
端口;
$ / code>
注册您的反序列化程序:
gsonBuilder.registerTypeAdapter(Port.class,new PortConverter());
Hi I'm having the following json data
{
"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"
}
}
]
}
I want to deserialize this json using gson.fromJson
. But the problem here is the port
sometimes holds a number and sometimes holds an object. How can I get the port
to get both object and the number?
解决方案 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 classes:
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;
}
Register your deserializer:
gsonBuilder.registerTypeAdapter(Port.class, new PortConverter());
这篇关于GSON用相同的名称解析具有不同类型数据的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文