尝试解析

时间:2017-03-24 12:07:22

标签: android json

我有从服务器返回的以下JSON字符串(下面)。 我可以成功提取resultCode值,这是" OK"。

我遇到的问题是提取user对象,它正在返回null。 我在SO上查看了以下文章,我相信我做得很好。

json example that i have tried

有人能指出我正确的方向吗?

{
    "resultCode":"OK",
    "configs":[
        {
            "configID":"1",
            "configName":"Data Limit",
            "configValue":"5000000"
        },
        {
            "configID":"2",
            "configName":"Connectivity Settings Frequency",
            "configValue":"55"
        },
        {
            "configID":"3",
            "configName":"User Tracking Frequency",
            "configValue":"56"
        },
        {
            "configID":"4",
            "configName":"Data Monitoring Frequency",
            "configValue":"57"
        },
        {
            "configID":"5",
            "configName":"User Device Frequency",
            "configValue":"58"
        },
        {
            "configID":"6",
            "configName":"Telephony Settings Frequency",
            "configValue":"59"
        },
        {
            "configID":"7",
            "configName":"Restrictions Settings Frequency",
            "configValue":"60"
        },
        {
            "configID":"8",
            "configName":"DateTime Settings Frequency",
            "configValue":"61"
        },
        {
            "configID":"9",
            "configName":"Advanced Settings Frequency",
            "configValue":"62"
        }
    ],
    "companyInfo":{
        "companyID":"1",
        "companyName":"Test Company",
        "webServiceGuid":"11E0662D-6672-406C-977A-4BE9124B3E35",
        "url":"http:\/\/xxx.yourofficeanywhere.co.uk\/",
        "portNumber":"51000"
    },
    "user":{
        "userID":"8",
        "samsungApiKey":"ABC",
        "surname":"Womersley"
    }

}

JSONObject mainObject = new JSONObject(result);
Log.e(TAG, "mainObject = " + mainObject);

resultCode = mainObject.get("resultCode").toString();
Log.e(TAG, "resultCode = " + resultCode);
cv.put("resultcode", resultCode);

JSONObject user = mainObject.getJSONObject("user");
Log.e(TAG, "user object = " + user);
String userID = user.getString("userID");
Log.e(TAG, "userID = " + userID);
cv.put("userid", userID);

[EDIT1] @flotto

JSONObject mainObject = new JSONObject(result);
Log.e(TAG, "mainObject = " + mainObject);
JSONArray arr = mainObject.names();

for(int i = 0; i < arr.length(); i++) {
    String name = arr.getString(i).toString();
    Log.e(TAG, "name = " + name);
}

结果:

03-24 12:19:34.702 2893-4899/d.co.uk.d E/WebService: name = resultCode
03-24 12:19:34.702 2893-4899/d.co.uk.d E/WebService: name = configs
03-24 12:19:34.702 2893-4899/d.co.uk.d E/WebService: name = companyInfo
03-24 12:19:34.702 2893-4899/d.co.uk.d E/WebService: name = user

2 个答案:

答案 0 :(得分:2)

在您阅读resultCode时调试代码。在那一刻&#34; mainObject&#34;应该包含用户JSON对象。如果它为空,那么您的服务器不会向您发送您正在等待的正确JSON。

答案 1 :(得分:-1)

我对所有人的批评,我没有实例化我的Contentsvalue,因此在尝试将resulCode添加到它时崩溃了。我忽略了一个简单的错误。谢谢大家的帮助

相关问题