繁体   English   中英

在Java for Android Studio中解析JSON的问题

[英]Issues parsing JSON in Java for Android Studio

我正在学习基本的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

您应该将源字符串转换为JSONArray而不是JSONObject
请尝试这个

    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.
    }

您的json是数组[],而不是对象{}

首先,您需要将JSON响应作为ArrayList,因为它以Array开头,即[]不是Object(大括号){}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM