Java JSON对象不能被初始化
我正在使用以下代码创建一个Java JSON对象不能被初始化,java,android,json,Java,Android,Json,我正在使用以下代码创建一个JSONObject,但即使在初始化之后,变量仍显示null: JSONObject jsonObject = new JSONObject(); try { jsonObject.put("username", "pradyut"); jsonObject.put("password", "5F4DCC3B5AA765D61D8327DEB882CF99"); } catch (JSONException e) { e.printStackTr
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 (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
正在检查它是否为null。如果为真,它将通过块中的else
否则。我想你打算改变现状。小错误……改变现状
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");
}
这是一种针对
if条件的日志语句错误的情况。if条件检查对象是否为null,但log语句打印出“json对象不是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-抛出一些异常}
检查此项
如果条件改变
如果(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");
}
您的if语句条件错误。==null表示它正在检查它是否为null。“但是变量即使在初始化之后也显示为null”不,不是。如果你说你看到的是消息
json对象为null
,那是因为你的If
是向后的。但是你不需要If
;在那段代码中,jsonObject
完全不可能null
。@intj:是的,希望他是这样做的,而不仅仅是r反复用电子邮件说“我做得很好”。@T.J.Crowder如果他不这样做,这会被贴上打字错误的标签,并且会被标记出来。@intj:是的,我也投了同样的票。这太糟糕了。显然有些问题,但如果信息不存在,我们也帮不上忙……嘿,这里出了什么问题……兄弟……代码转储不是有用的答案。说出你改变了什么,以及为什么。(也就是说,这个问题目前无法得到合理的回答。在其当前状态下,由于OP未能澄清它,因此应该关闭并删除它。)谢谢先生为我提供的帮助。我会记住它的。再次感谢。我没有看这部分。但日志字符串是错误的。