我正在尝试显示来自 JSONData 的 JsonArray 值
JSON 数据
{"error":{"group_name":["The group name has already been taken."]}}
这是我的代码
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseStr);
Log.d("Checking Login", responseStr);
JSONArray jsonArray = json.getJSONArray("group_name");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
}
我遇到这样的异常
org.json.JSONException: No value for group_name
最佳答案
error
是嵌套的 JSONObject
包含您的 JSONArray
JSONObject json = new JSONObject(responseStr);
JSONObject json1 = json.getJSONObject("error");
// ^^^^^ fetch nested JSON
JSONArray jsonArray = json1.getJSONArray("group_name");
for(int i = 0; i<jsonArray.length();i++){
// JSONObject jsonObject = jsonArray.getJSONObject(i); error
// jsonArray has no JSONOBJECT but it has String
}
注意:您的 group_name
JSONArray 没有 jsonObjects
而不是根据您展示的示例只有一个 String
所以 jsonArray .getJSONObject(i)
将导致异常。
{"error":{"group_name":["The group name has already been taken."]}}
|---------------String-----------------|
|---------------JSONOArray---------------|
|-----------------Nested JSONOBJECT---------------------|
|------------------------JSONOBJECT-------------------------------|
所以你的 JSONArray
中只有 String
所以使用 optString
获取您的 String
JSONObject json = new JSONObject(responseStr);
JSONObject json1 = json.getJSONObject("error");
// ^^^^^ fetch nested JSON
JSONArray jsonArray = json1.getJSONArray("group_name");
for(int i = 0; i<jsonArray.length();i++){
String str = jsonArray.optString(i);
}
关于java - 无法显示来自 JSONData 的 Json 数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41713756/