我在http://susana.iovanalex.ro/esculap/ws2.php?key=abc&action=getpatientlist有一个REST Web服务,它返回类似于下面的JSON有效负载:
[{"id":"15","nume":"Suciu","prenume":"Monica","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"60","alarm_pulse_max":"90","alarm_oxy_min":"90"},
{"id":"101","nume":"Test Node","prenume":"Arduino","location":"UPT Electro,
B019","alarm_pulse_min":"50","alarm_pulse_max":"160","alarm_oxy_min":"93"},
{"id":"160","nume":"Vasilescu","prenume":"Ion","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"60","alarm_pulse_max":"120","alarm_oxy_min":"80"},
{"id":"161","nume":"Lungescu","prenume":"Simion","location":"Pneumologie, Salon 5, Pat
5","alarm_pulse_min":"70","alarm_pulse_max":"110","alarm_oxy_min":"95"},
{"id":"162","nume":"Paunescu","prenume":"Ramona","location":"Cardiologie, Salon 4, Pat
2","alarm_pulse_min":"0","alarm_pulse_max":"0","alarm_oxy_min":"0"}]
在遵循http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/的教程时使用Android的解析器时,我想在ArrayList中返回已处理的数据。
我经常收到以下错误:
org.json.JSONException: Value [{"prenume":"Monica", ... "nume":"Paunescu"}] of type
org.json.JSONArray cannot be converted to JSONObject.
你能不能给我一个代码片段或指针,我在哪里可以找到更多信息?
答案 0 :(得分:3)
你的整个Json是一个JSONArray的JSONObjects。
你试图获得一个JSON对象,即:
JSONObject jObject = new JSONObject("[{"prenume":"Monica", ... "nume":"Paunescu"}]");
但那是一个数组!
尝试:
JSONArray jArray = new JSONArray("[{"prenume":"Monica", ... "nume":"Paunescu"}]");
for(int i=0; i < jArray.length(); i++){
JSONObject jObject = jArray.getJSONObject(i);
String prenume = jObject.getString("prenume");
Log.i("TAG", "Prenume is: "+ prenume);
}
答案 1 :(得分:1)
请参阅此处http://www.json.org/您的网络服务包含json数组,而不是json对象,因此解析为:
JSONArray JSONArrays = new JSONArray(jString);
for(int n = 0; n < JSONArrays.length(); n++)
{
JSONObject object = JSONArrays.getJSONObject(n);
// do some stuff....
}
答案 2 :(得分:1)
最好的办法是使用GSON解析您收到的JSONAray字符串作为输出。这有助于您将数据作为真实对象进行管理,而不是字符串。
请查看以下帖子来解析您的JSON数组
How to Parse JSON Array in Android with Gson
您唯一需要做的就是使用JSON输出中的参数名称创建Classes
答案 3 :(得分:0)
您可以参考此链接
https://stackoverflow.com/a/11446076/1441666
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
以下是我提取国家/地区详情
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
答案 4 :(得分:0)
我认为你应该更好地使用一个可以处理REST请求和对象序列化/反序列化的库。 看看Push Messages using REST api in android