![](/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.