我正在使用Android应用程序,我收到来自Web服务的基于json的响应。当webservice作为json数组返回多个记录时,一切都很好,当Web服务开始发送只有一条记录的数据并且它作为json对象发送时,问题就开始了。在客户端我无法预测数量返回的记录(如1或大于1)我想找到一个适应两种条件的解决方案。下面的代码是我用来在有多个记录时解析数据的代码,
get_response = new JSONObject(webservice_out);
JSONArray inventory_data = get_response.getJSONArray("inventorydata");
Log.e("inventory", inventory_data.toString());
for (int j = 0; j < inventory_data.length(); j++)
{
JSONObject e1 = inventory_data.getJSONObject(j);
Log.e("names", e1.getString("itemName"));
JSONObject e3 = e1.getJSONObject("passenger");
}
在上面的代码中,“inventorydata”是作为来自webservice的响应返回的json值之一,每当“inventorydata”只保留一条记录作为响应时它作为json对象发送,当它有多于1条记录时作为json数组发送。由于响应中的记录数是动态的,我想根据webservie的响应找到一个可以同时包含(json对象和数组)的解决方案。
注意:我没有权限对网络服务进行更改
答案 0 :(得分:2)
您有两种选择:
请改用get_response.optJSONArray()
,然后检查它是否为null
。如果是,请回退到getJSONObject()
。
JSONArray inventory_data = get_response.optJSONArray("inventorydata");
if (inventory_data == null) {
// process json array
} else {
JSONObject jsonObject = get_response.getJSONObject("inventorydata");
// process json object
}