JSONObject中取String 值的幾種方法和對比
阿新 • • 發佈:2019-01-28
今天寫程式碼的時候發現以前寫JSON中取String值喜歡這樣寫:
String kewen = (String)test.get("kewen");
其實這樣寫比較挫,一般來說JSON物件中取String型別的值有這兩種方法:
test.getString("name");
test.optString("name");
然後來看一下這兩種方法有什麼不同
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." );
}