[英]How to parse object which is sometimes Json object and sometimes json Array
I working with API in which an object can an be array or it can be any object and I don't know in which scenario it will be object or array so i can't use different object base on some condition. 我使用的API中的对象可以是数组,也可以是任何对象,我不知道在哪种情况下它将是对象或数组,因此在某些情况下我不能使用其他对象。
Unfortunately I've no access to API code so I can't do any changes there. 不幸的是,我无权访问API代码,因此无法在那里进行任何更改。 Any trick that I've to do will be on client side. 我要做的任何技巧都将在客户端。
So what is the best way to handle that scenario. 那么处理这种情况的最佳方法是什么。
Edit : Response Example 编辑 :响应示例
.
.
"ecf":"0",
"place":{ },
"mn":"1st Test",
"teams":[ ],
"past_ings":[
{
"s":{ },
"d":{
"a":{
"t":{
"i":"5221",
"a":"3",
"c":"not out",
"dt":null,
"fd":"0",
"bd":"0",
"cb":"no",
"b":"1",
"r":"0",
"sr":"0",
"four":"0",
"six":"0",
"name":"Umesh Yadav"
}
}
}
}
.
.
The object t can be array or it can be object. 对象t可以是数组,也可以是对象。
Note : I'm using Gson for parsing and using Retrofit in my network layer. 注意:我在网络层中使用Gson进行解析和使用Retrofit。
Object response = json.get("response")
if (response instanceof JSONArray) {
// It's an array, cast it as a JSONArray to use it.
} else {
// It's an object, cast it as a JSONObject to use it.
}
Just define this is Object when parse json by Gson in Java. 只需在用Java解析Gson的json时将其定义为Object即可。 After that you have manual if then object is array or object. 之后,如果对象是数组或对象,则可以使用手册。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.