首页 > 解决方案 > 在 Java for Android Studio 中解析 JSON 的问题

问题描述

我正在学习基本的 Java 应用程序创建,并且认为到目前为止我做得还不错,但是我在解析来自服务器的 JSON 响应方面有所下降。

我什至不确定我的回答是否正确。

响应表单服务器:

[{"Q_Number":"1","Question":"This is Q1"},{"Q_Number":"2","Question":"This is Q2"},{"Q_Number":"3","Question":"This is Q3"}]

如您所见,我收到了服务器给出的三个问题,标记为 1 - 3。理想情况下,我希望将 JSON 解析为标记为:的字符串q1String q2String q3String

我在这里尝试了各种解析代码形式,并试图让它对我有用。这是我当前的混乱代码:

String jsonString = a.toString();
    try {
JSONObject json = new JSONObject(jsonString);

        JSONObject jsonOb = json.getJSONObject("1");

        String str_value=jsonOb.getString("Question");

        Log.i("JSON",str_value);

    } catch (JSONException e) {
        Log.e("MYAPP", "unexpected JSON exception", e);
        // Do something to recover ... or kill the app.
    }

这是我得到的最后一个错误:

org.json.JSONException: Value [{"Q_Number":"1","Question":"This is Q1"},{"Q_Number":"2","Question":"This is Q2"},{"Q_Number":"3","Question":"This is Q3"}] of type org.json.JSONArray cannot be converted to JSONObject

标签: javaandroidjson

解决方案


您应该将源字符串转换为JSONArraynotJSONObject
请试试这个

    String jsonString = a.toString();
    try
    {
        JSONArray json = new JSONArray(jsonString);
        for(int index = 0; index < json.length(); ++index)
        {
            JSONObject obj = json.getJSONObject(index);
            String str_value = obj.getString("Question");
            Log.i("JSON", str_value);
        }
    }
    catch (JSONException e)
    {
        e.printStackTrace();
        // Do something to recover ... or kill the app.
    }

推荐阅读