java - 无法显示来自 JSONData 的 Json 数组值

标签 java android arrays json http

我正在尝试显示来自 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/

相关文章:

java - 如何设置一个 JFrame 中两个 JPanel 的大小?

java - 我可以告诉 gradle 两个不同的依赖模块实际上是相同的并让它选择版本最高的那个吗?

java - 安装 Project Lombok 后处理 RealmObject 后代时出错

javascript - Google map 的 KML 坐标

java - 将 Set<Object> 转换为 Collection<String>

c# - 如何将该运算符 C# 代码表示为 java?

android - 如何为应用程序实现更改主题?

android - BottomNavigationView 在 Snackbar 出现时移动

c - 如何拆分多行字符串并将它们存储到C中的json数组中

c++ - 用 C++ 返回两个数组