Creating new JSONObject from String Returns Null - JAVA / Android

匿名 (未验证) 提交于 2019-12-03 01:48:02

问题:

I'm attempting to create a new JSONObject from a String however for some reason the new JSONObject is always null - and I'm unsure why.

Any suggestions are appreciated.

Source:

JSONObject messagesObj;       String mArr = intent.getStringExtra("msgArr");              try {                 if (mArr != null)                     messagesObj = new JSONObject(mArr);                  if (messagesObj != null)                     populateMessages(messagesObj);                 DataManager.clientChatMarkMessagesSeen(chatId);             } catch (JSONException e) {             //    DataManager.clientChatLoad(this);                 e.printStackTrace();             } 

Values:

String mArr = [{"message":"User has joined the chat.","type":"agent","created":"2016-12-07 17:35:09","name":"User"},{"message":"Hello World?","type":"agent","created":"2016-12-07 17:35:17","name":"User"},{"message":"User has left the chat.","type":"agent","created":"2016-12-07 17:38:40","name":"User"}] 

回答1:

Because that isn't a json object- its a JSONArray. Try creating a JSONArray instead of a JSONObject



回答2:

The string is json array not object..please see the root node it is not {}

Modify the string like this array of objects

String mArr = {"results": [{"message":"User has joined the chat.","type":"agent","created":"2016-12-07 17:35:09","name":"User"},{"message":"Hello World?","type":"agent","created":"2016-12-07 17:35:17","name":"User"},{"message":"User has left the chat.","type":"agent","created":"2016-12-07 17:38:40","name":"User"}]}



回答3:

Use JSONArray array = new JSONArray("string here"). It's an array if it starts with square brackets.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!