我正在学习基本的 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
3 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
您应该将源字符串转换为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.
}
添加回答
举报
0/150
提交
取消