1. 程式人生 > >JSON中的get和opt方法的區別

JSON中的get和opt方法的區別

區別

  • 不想拋異常,不適用try{}catch,請適用opt方法
  • 相反,使用get方法,會拋異常,需要try一下

json中的opt和get方法 ##

  • get()和opt()
  • getBoolean()和optBoolean();
  • getDouble()和optDouble();
  • getInt()和optInt();
  • getLong()和optLong();
  • getString()和optString();
  • getJSONObject和optJSONobject();
  • getJSONArray和optJSONArray();

程式碼中區別

  public JSONArray getJSONArray
(String name) throws JSONException { Object object = get(name); if (object instanceof JSONArray) { return (JSONArray) object; } else { throw JSON.typeMismatch(name, object, "JSONArray"); } }
public JSONArray optJSONArray(String name) {
        Object object
= opt(name); return object instanceof JSONArray ? (JSONArray) object : null; }

總結

今天工作中看到領導寫的程式碼發現其用opt方法,隨口一問,領導笑而不語,對於有經驗的人來說,我們的問題可能很可(S)笑(B)。確實,只能內心默默的謹記加倍的努力。
別人確實沒有義務回答你問題,但一種精神我覺得值得發揚:幫助別人不求回報,只求在別人困難的時候請伸手幫一把。能力很菜,但是能解決的問題,肯定幫助別人,就感到高興。