[英]Issues parsing JSON in Java for Android Studio
I am learning basic Java app creation and think I'm doing ok so far, however I have fallen in regards to parsing a JSON response from a server. 我正在学习基本的Java应用程序创建,并且到目前为止我认为还不错,但是在解析服务器的JSON响应方面我已经陷入困境。
I'm not even sure my response is built correctly. 我什至不确定我的回复是否正确。
Response form server: 响应表单服务器:
[{"Q_Number":"1","Question":"This is Q1"},{"Q_Number":"2","Question":"This is Q2"},{"Q_Number":"3","Question":"This is Q3"}]
As you can see I get three questions given by the server, labeled 1 - 3. ideally what I'd like is the JSON to be parsed into string labeled: q1String q2String q3String
. 如您所见,服务器收到三个问题,标记为1-3。理想情况下,我希望将JSON解析为标记为的字符串:
q1String q2String q3String
。
I have tried a variety of parsing code form here and tried to make it work for me. 我在这里尝试了各种解析代码形式,并试图使其对我有用。 Here is my current messy code:
这是我当前的混乱代码:
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.
}
This is the last error I got: 这是我得到的最后一个错误:
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
You should convert the source string to JSONArray
not JSONObject
您应该将源字符串转换为
JSONArray
而不是JSONObject
Please try this 请尝试这个
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.