我有一个 Android 应用程序,我在其中从 API 获取了一些 JSON,现在我需要对其进行解码。我很远,但我无法获取内容。我收到的 JSON 如下所示:
{ "messages": [
{
"created": "1391783287",
"id": 1,
"is_supporter": false,
"text": "Behold! This is a message?"
},
{
"created": "1391783287",
"id": 3,
"is_supporter": true,
"text": "Behave! This is an answer!"
}
]}
我有这段代码:
@Override
protected void onPostExecute(String result) {
try{
JSONArray jArray = new JSONArray(result);
在上面代码的最后一行,我收到一条错误消息:Error: org.json.JSONException: Value {"messages":[{"id":1,"created":"1391788514", "text":"我如何向 IBAN 付款?","is_supporter":false},{"id":3,"created":"1391788514","text":"什么是支付池?", org.json.JSONObject 类型的 "is_supporter":false}]} 无法转换为 JSONArray
有没有人知道这里出了什么问题或者我该如何解决这个问题?
最佳答案
您的字符串是一个包含 JSON 数组的 JSON 对象,试试这个:
JSONObject myJSON = new JSONObject(result);
JSONArray jArray = myJSON.getJSONArray("messages");
然后遍历您的 JSONArray ...
int size = jArray.length();
for (int i=0 ; i<size ; i++){
JSONObject itemInArray = jArray.get(i);
// get values inside the object, for example :
String text = itemInArray.getString("text");
}
关于Java:如何在 Android 中解码 JSON?我究竟做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21632719/