Android JSON解析引发意外异常

时间:2016-11-22 01:58:05

标签: android arrays json

来源:

try {
  JSONArray jsonArray = new JSONArray(intent.getStringExtra("chatData"));

  for (int i = 0; i < jsonArray.length(); i++) {
    JSONObject item = jsonArray.getJSONObject(i);
    messagesArr = new JSONArray(item.getString("message"));
    messagesObj = new JSONObject();
    messagesObj.put("messages", messagesArr);
    populateMessages(messagesObj);
  }
} catch (Exception e) {

}

我还尝试更改以下行但没有成功:

messagesArr = new JSONArray(item.getJSONObject("message"));

任何建议都表示赞赏。

值:

item =  {"message":"User has joined.","type":"agent","created":"2016-11-21 20:55:22","name":"Username"}

logcat的:

1-21 21:15:40.775 23532-23532/com.example.examplemobile W/System.err: org.json.JSONException: Value Johnny of type java.lang.String cannot be converted to JSONArray
11-21 21:15:40.775 23532-23532/com.example.examplemobile W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
11-21 21:15:40.785 23532-23532/com.example.examplemobile W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
11-21 21:15:40.785 23532-23532/com.example.examplemobile W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)

3 个答案:

答案 0 :(得分:1)

您尝试将String解析为JSONArray,这就是它抛出异常的原因。要将其解析为JSONArray,您必须拥有以下数据:{ "message":["String1", "String2", "String3"] }

将您的messagesArr变量更改为字符串,然后访问&#34;消息&#34;字符串调用messagesArr = item.getString("message");

答案 1 :(得分:1)

根据您在评论中提供的json字符串,它不是有效的json字符串

[{"type":"agent","message":"User has joined the chat.","created":"2016-11-21 21:40:31","name":"User"},{"type":"agent","message":"example message,"created":"2016-11-21 21:40:36","name":"User"},{"type":"agent","message":"User has left the chat.","created":null,"name":"User"}]

example message

之后需要一个双引号

尝试将json字符串更改为

[
  {
    "type": "agent",
    "message": "User has joined the chat.",
    "created": "2016-11-21 21:40:31",
    "name": "User"
  },
  {
    "type": "agent",
    "message": "example message",
    "created": "2016-11-2121: 40: 36",
    "name": "User"
  },
  {
    "type": "agent",
    "message": "Userhasleftthechat.",
    "created": null,
    "name": "User"
  }
]

让我知道结果

答案 2 :(得分:0)

我认为您需要将String JSON intent.getStringExtra("chatData")转换为JSON数组。

也许这个链接可以提供帮助 Convert String To JSON Array