![](/img/trans.png)
[英]How to parse a json in which the object sometime acts as a string or an array in Retrofit
[英]How to parse JSON if an element is coming as jsonobject sometime and jsonarray sometime
我有来自服务的json响应。 对于某个元素,它有时会作为json数组传入,而有时它会作为json对象传入。
例:
Response 1:
{"_id":2,"value":{id: 12, name: John}}
Response 2:
{"_id":1,"value":[{id: 12, name: John}, {id: 22, name: OMG}]}
这里的值是响应1中的jsonObject和响应2中的jsonArray。
问题是我正在使用Gson解析json。 并将值保存为我的POJO类中的ArrayList。
public class ResponseDataset {
private int _id;
private ArrayList<Value> value;
// getter setter
}
public class Value {
private int id;
private String name;
// getter setter
}
有什么我可以使用Gson处理的方法吗? 我的json响应太大和太复杂,因此想避免逐行解析。
即使我遇到了同样的问题,我也做了以下工作。
String jsonString = "{\"_id\":1,\"value\":[{id: 12, name: John}, {id: 22, name: OMG}]}";
JSONObject jsonObject = new org.json.JSONObject(jsonString);
ResponseDataset dataset = new ResponseDataset();
dataset.set_id(Integer.parseInt(jsonObject.getString("_id")));
System.out.println(jsonObject.get("value").getClass());
Object valuesObject = jsonObject.get("value");
if (valuesObject instanceof JSONArray) {
JSONArray itemsArray =(JSONArray) valuesObject;
for (int index = 0; index < itemsArray.length(); index++) {
Value value = new Value();
JSONObject valueObject = (JSONObject) itemsArray.get(index);
value.setId(Integer.parseInt(valueObject.getString("id")));
value.setName(valueObject.getString("name"));
dataset.getValue().add(value);
}
}else if(valuesObject instanceof JSONObject){
Value value = new Value();
value.setId(Integer.parseInt(((JSONObject)valuesObject).getString("id")));
value.setName(((JSONObject)valuesObject).getString("name"));
dataset.getValue().add(value);
}
你可以试试看
在这里找到解决方案Gson处理对象或数组
@Pasupathi您的解决方案也是正确的,但我想使用Gson的方法,因为我的服务响应太大且太复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.