【问题标题】:JSON object can not be inintialised [closed]JSON对象无法初始化[关闭]
【发布时间】:2016-06-23 08:08:54
【问题描述】:

我正在使用以下代码创建一个JSONObject,但变量即使在初始化后仍显示null

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("username", "pradyut");
    jsonObject.put("password", "5F4DCC3B5AA765D61D8327DEB882CF99");
} catch (JSONException e) {
    e.printStackTrace();
    Log.i("log", "json exception : " + e.toString());
}


if (jsonObject == null) {
    Log.i("log", "the json object is not null");
    // this part is showing everytime.
} else {
    Log.i("log", "the json object is null");
}

我没有遇到任何异常。

为什么会这样?

【问题讨论】:

  • 你的 if 语句条件错误。 == null 表示它正在检查它是否为空。
  • "但变量在初始化后仍显示为 null" 不,不是。如果您说您看到消息the json object is null,那是因为您的if 落后了。但是你不需要if;在那段代码中,jsonObject 根本不可能是 null
  • @intj:是的,希望他能做到,而不是反复重申“我做的一切都是对的”。
  • @T.J.Crowder 如果他不这样做,则可以将其标记为拼写错误并进行标记。
  • @intj:是的,我投了同样的票。这太糟糕了。显然存在一些问题,但如果信息不存在,我们将无能为力......

标签: java android json


【解决方案1】:

你的条件不对。

if (jsonObject == null) {
    Log.i("log", "the json object is not null");
    // this part is showing everytime.
} else {
    Log.i("log", "the json object is null");
}

jsonObject == null 正在检查它是否为空。如果是真的,它将通过块,否则else。我认为你打算扭转这种情况。

【讨论】:

  • 谢谢。我没有看这部分。但是日志字符串是错误的。
【解决方案2】:

这是if-condition 的日志语句错误的情况。您的 if 条件检查对象是否为空,但日志语句会打印 "the json object is not null",这完全是误导。

你的 if 块应该是这样的:

  if (jsonObject != null) {
        Log.i("log", "the json object is not null");      
    } else {
        Log.i("log", "the json object is null");
    }

这里的教训是,与其打印“is not null”或“is null”之类的语句,不如打印实际变量本身——比如Log.i("jsonObject :"+jsonObject)——只有当你需要根据值做某事时,你可以有if(jsonObject !=null) {do-stuff}else{ log-error or -throw-some-exception}

【讨论】:

    【解决方案3】:

    检查一下

    改变条件 if (jsonObject.length()!=0) {它会帮助你

    JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("username","pradyut");
                jsonObject.put("password", "5F4DCC3B5AA765D61D8327DEB882CF99");
            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("log", "json exception : " + e.toString());
            }
    
    
    
            if (jsonObject.length()!=0) {
                Log.i("log", "the json object is not null");
                // this part is showing every time.
            } else {
                Log.i("log", "the json object is null");
            }
    

    【讨论】:

    • 代码转储不是有用的答案。说出您更改了什么,以及为什么。 (也就是说,这个问题目前无法得到合理的回答。在目前的状态下,由于OP未能澄清它,因此应该关闭并删除它。)
    • 感谢先生对我的帮助指导,我会记住的,再次感谢。
    【解决方案4】:

    小错误...改变条件

     if (jsonObject != null) {
            Log.i("log", "the json object is not null");
            // this part is showing every time.
        } else {
            Log.i("log", "the json object is null");
        }
    

    【讨论】:

    • 嘿Whatswrong 这里.. 兄弟..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-07
    相关资源
    最近更新 更多