【问题标题】:Error Parse JSON Response String Android错误解析 JSON 响应字符串 Android
【发布时间】:2013-03-17 16:37:27
【问题描述】:

我有一个来自这样的 API 服务的响应字符串:

{"id":"login","status":"true"}

这是解析响应字符串以从键“状态”获取值的方法

                    JSONObject jsonObj = null;
    try{
        jsonObj = new JSONObject(responseString);
    }
    catch(JSONException e){
        e.printStackTrace();


    }


        JSONArray innerJsonArray = null;
        try {
            innerJsonArray = jsonObj.getJSONArray("status");
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = innerJsonArray.getJSONObject(0);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            System.out.println(jsonObject.getString("status"));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我有错误 "org.json.JSONArray 无法转换为 JSONObject"

谁能给我建议?

【问题讨论】:

  • 使用getBoolean() 而不是getJSONArray()...
  • 显然错误指出您正在尝试将 Jsonobject 转换为 JsonArray 。因为当前字符串仅包含 jsonobject

标签: java android arrays json response


【解决方案1】:
JSONObject jsonObj = null;
try{
    jsonObj = new JSONObject(responseString);
    System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
    e.printStackTrace();
}

您无需为任何其他数组操心。

【讨论】:

    【解决方案2】:

    请尝试下面的 sn-p 代码。试试这个link 以获得关于解析 JSON 响应的更多知识。

    JSONObject jObj;
            try {
                jObj = new JSONObject(responseString);
                Log.i("id==", jObj.getString("id"));
                Log.i("status==", jObj.getString("status"));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    

    【讨论】:

      【解决方案3】:

      你在哪一行得到了异常?无论如何,你应该使用

      jsonObj =JSONObject.fromObject(responseString);

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 2014-04-12
        • 2017-09-28
        • 2013-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多