2011/03/28

JSONObject的取值與容錯

最近出了一個包,在此記錄

在Server端傳JSONObject時以getType去取值且沒有先檢查該值是否存在
當Server端修改資料少將某欄位拔掉
就直接JSONException了
當初沒有想到這種狀況所以出包了

後來查了 一下官方API看到下面兩句話
  • Use getType() to retrieve a mandatory value. This fails with a JSONException if the requested name has no value or if the value cannot be coerced to the requested type. 
  • Use optType() to retrieve an optional value. This returns a system- or user-supplied default if the requested name has no value or if the value cannot be coerced to the requested type.
當初應該要用optType才對,不過還是要慎用
比方optDouble (String name)當沒有值時傳回的是NaN
感覺也是有風險

當然自行處理JSONException也是可行的
只是我漏了且那種狀況要用Exception處理未免過於繁瑣


Ref:
http://developer.android.com/reference/org/json/JSONObject.html

沒有留言 :