在 Java 中为 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



MMMHUHU
浏览 200回答 3
3回答

料青山看我应如是

您应该将源字符串转换为JSONArraynotJSONObject请试试这个&nbsp; &nbsp; String jsonString = a.toString();&nbsp; &nbsp; try&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; JSONArray json = new JSONArray(jsonString);&nbsp; &nbsp; &nbsp; &nbsp; for(int index = 0; index < json.length(); ++index)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; JSONObject obj = json.getJSONObject(index);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String str_value = obj.getString("Question");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.i("JSON", str_value);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; catch (JSONException e)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; // Do something to recover ... or kill the app.&nbsp; &nbsp; }

手掌心

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

BIG阳

首先,您需要将 JSON 响应作为 ArrayList,因为它以 Array 开始,即 [] 不是对象(花括号){}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java