大話 JSON 之 JSONObject.getString(“”) 方法 和 JSONObject.optString(“”) 的區別


運行以下代碼:

public static void main(String[] args)  
{  
    JSONObject test = new JSONObject();  
    test.put("name", "kewen");  
    test.put("empty", null);  
  
    System.out.println("test.optString(\"empty\"):" +test.optString("empty"));  
    System.out.println("test.optString(\"name\"):" +test.optString("name"));  
    System.out.println("test.getString(\"name\"):" + test.getString("name"));  
    System.out.println("test.getString(\"empty\"):" + test.getString("empty"));  
}  

  運行一把就會看到這樣的結果 、

test.optString("empty"):  
test.optString("name"):kewen  
test.getString("name"):kewen  
Exception in thread "main" net.sf.json.JSONException: JSONObject["empty"] not found.  
    at net.sf.json.JSONObject.getString(JSONObject.java:2247)  
    at basicUtils.JSONUtil.main(JSONUtil.java:41)  

  因為:在JSONObjecy的key存在值得時候,兩者是沒有什么區別的,然后如果key對應的value為null,那么getString方法就會報錯。

至於為什么會這樣我們可以看一下getString的源碼

public String getString( String key ) {  
   verifyIsNull();  
   Object o = get( key );  
   if( o != null ){  
      return o.toString();  
   }  
   throw new JSONException( "JSONObject[" + JSONUtils.quote( key ) + "] not found." );  
}  

 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM