JSON: -
{
"events": ["wedding", "wed"],
"event_location": ["", ""],
"event_studio": [
["makeover", "epica", "Raddisson"],
["makeover", "epica"],
["Raddisson", "makeover", "contours"]
],
"event_studio_location": [
["Ernakulam", "thrissur", "kollam"],
["Ernakulam", "thrissur"],
["kollam", "Ernakulam", "Malappuram"]
]
}
想要从json获取事件并将其存储在字符串数组中。
String[] a=new String[responseBody.getJSONArray("events").length()];
a=responseBody.getJSONArray("events");
显示错误不兼容的类型需要找到的字符串找到json数组
答案 0 :(得分:0)
您无法直接将jsonarray转换为String数组。您可以使用此函数将jsonarray转换为String:
public static String[] toStringArray(JSONArray array) {
if(array==null)
return null;
String[] arr=new String[array.length()];
for(int i=0; i<arr.length; i++) {
arr[i]=array.optString(i);
}
return arr;
}
这将解决您的问题。
答案 1 :(得分:0)
检查JsonString对象是即将发布的Json String,JsonObjct还是JsonArray。通过instanceof
并在JSONTokener
如同下面的代码
Object object = new JSONTokener(jsonString).nextValue();
if (object instanceof JSONObject)
{
JSONObject jsonObject = (JSONObject) object;
}
else if (object instanceof JSONArray)
{
JSONArray jsonArray = (JSONArray) object;
}
答案 2 :(得分:-1)
尝试以下代码
try {
JSONObject jsonObject = new JSONObject(responseBody);
JSONArray jsonArray = jsonObject.getJSONArray("events");
String[] arrayEvents=new String[jsonArray.length()];
for(int i=0; i<arrayEvents.length; i++) {
arrayEvents[i]=jsonArray.optString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}