大家好,这是我的json回复:
[
{
"Woa": [
"Seo",
"Rikjeo",
"JDa"
]
},
"Aha",
"Aad",
"Char"
]
我想添加Woa的列表字符串:
{
"Woa": [
"Seo",
"Rikjeo",
"JDa"
]
}
这是我到目前为止所做的:
JSONObject object = new JSONObject(result);
JSONArray a = object.getJSONArray("Woa");
for (int i = 0; i < a.length(); ++i) {
listWoa.add(a.getString(i));
}
但是我收到了这个错误:
type org.json.JSONArray cannot be converted to JSONObject
任何想法,为什么我没有得到任何字符串,也无法转换为JSONObject。
答案 0 :(得分:3)
解析json响应之上。请尝试以下代码:
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObjWoa = jsonArray.getJSONObject(0);
JSONArray jsonArrayWoa = jsonObjWoa.getJSONArray("Woa");
for (int i = 0; i < jsonArrayWoa.length(); ++i) {
listWoa.add(jsonArrayWoa.getString(i));
}
答案 1 :(得分:2)
您的JSON是一个数组(“事物”列表),其中第一个项目是对象
[ << This is an array (let's call it A)
{ << This is A[0]
"Woa": [
"Seo",
"Rikjeo",
"JDa"
]
},
"Aha", << This is A[1] == "AhA"
"Aad", << This is A[2] == "aad"
"Char" << This is A[3] == "Char"
]
因此,A [0]是对象:
{ << This is an object ( A[0] )
"Woa": [ << This is A[0].Woa (it's an array)
"Seo", << This is A[0].Woa[0] == "Seo"
"Rikjeo", << This is A[0].Woa[1] == "Rikjeo"
"JDa" << This is A[0].Woa[2] == "JDa"
]
}
不在JSON中混合数组和对象的简单方法是:
[...] is an array
{...} is an object
答案 2 :(得分:1)
做这样的事情:
JSONArray jsonArray = new JSONArray(result);
JSONObject object = new JSONObject(jsonArray.get(0).toString());// if you have only one element then get 0th index
JSONArray a = object.getJSONArray("Woa");
for (int i = 0; i < a.length(); ++i) {
listWoa.add(a.getString(i));
}
答案 3 :(得分:0)
从我的角度来看:我会使用GSON自动解析JSON和这个站点来生成POJO。
http://www.jsonschema2pojo.org/ 确保单击:GSON作为注释样式,并使用JSON而不是JSON Scheme