2016-06-23 22 views
-5

我創建與下面的代碼JSONObject但可變正顯示出甚至其初始化後nullJSON對象不能inintialised

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"); 
} 

我沒有得到任何的異常。

這是爲什麼發生?

+8

你的if語句的條件是錯誤的。 == null意味着它檢查它是否爲空。 –

+0

運行這段代碼沒有錯誤?任何日誌/調試信息? –

+0

如果你不導出到json,你可能會考慮使用字典嗎? – David

回答

3

你的情況是錯誤的。

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。我想你打算扭轉這種狀況。

+0

謝謝。我沒有看這部分。但日誌字符串是錯誤的。 –

-1

小失誤......變化情況

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"); 
    } 
+0

嘿Whatswrong here .. bro .. – Kush

0

這是一種針對if-condition錯誤日誌語句的情況。您的if條件會檢查對象是否爲空,但日誌語句打印出的是完全誤導的"the json object is not null"

你如果塊應該是這樣的:

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

這裏的教訓是,而不是打印出來像一個聲明「不爲空」或「空」的,而打印的實際變量本身 - 象Log.i("jsonObject :"+jsonObject) - 那麼只有當你需要根據這個值做一些事情時,你纔可以有if(jsonObject !=null) {do-stuff}else{ log-error or -throw-some-exception}

0

檢查這個

變化,如果條件 如果(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"); 
     } 
+2

代碼轉儲不*有用*答案。說*你改變了什麼,以及*爲什麼*。 (也就是說,這個問題目前還不能合理回答,在目前的情況下,由於OP沒有澄清,所以應該關閉並刪除它。) –

+0

謝謝您的主席對我的幫助我將繼續它在心裏再次感謝。 – Sach