简体   繁体   English

从字符串创建新的JSONObject返回Null-JAVA / Android

[英]Creating new JSONObject from String Returns Null - JAVA / Android

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. 我正在尝试从字符串创建新的JSONObject,但是由于某种原因,新的JSONObject始终为null-但我不确定为什么。

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

Because that isn't a json object- its a JSONArray. 因为这不是json对象,所以它是JSONArray。 Try creating a JSONArray instead of a JSONObject 尝试创建JSONArray而不是JSONObject

The string is json array not object..please see the root node it is not {} 字符串是json数组,不是object ..请查看根节点,它不是{}

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"}]} 字符串mArr = {“结果”:[{“消息”:“用户已加入聊天。”,“类型”:“代理”,“创建”:“ 2016-12-07 17:35:09”,“名称“:” User“},{” message“:” Hello World?“,” type“:” agent“,” created“:” 2016-12-07 17:35:17“,” name“:” User“ },{“ message”:“用户已退出聊天。”,“ type”:“代理”,“创建”:“ 2016-12-07 17:38:40”,“ name”:“ User”}] }

Use JSONArray array = new JSONArray("string here"). 使用JSONArray array = new JSONArray(“ string here”)。 It's an array if it starts with square brackets. 如果以方括号开头,则为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM