1

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
  • 1
    It's not a JSONObject though, it's a JSONArray. Commented Dec 8, 2016 at 16:27

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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"}]}

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.