運行以下代碼:
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." );
}
