【问题标题】:Differences between optJSON and getJSON [duplicate]optJSON 和 getJSON 之间的区别 [重复]
【发布时间】:2016-10-05 15:02:55
【问题描述】:
String strJson="{
             \"Employee\" :[
             {
                \"id\":\"01\",
                \"name\":\"Gopal Varma\",
                \"salary\":\"500000\"
             },
             {
                \"id\":\"02\",
                \"name\":\"Sairamkrishna\",
                \"salary\":\"500000\"
             },
             {
                \"id\":\"03\",
                \"name\":\"Sathish kallakuri\",
                \"salary\":\"600000\"
             }
             ] 
          }";
    try {
        JSONObject  jsonObject = new JSONObject(strJson);
        JSONArray jsonArray1=jsonObject.optJSONArray("Employee");
        JSONArray jsonArray2=jsonObject.getJSONArray("Employee");
        } catch (JSONException e) {
          e.printStackTrace();
        }

在上面的示例中,optJSONArray("Employee") 和 getJSONArray("Employee") 都返回 JSONArray 有什么区别?

【问题讨论】:

    标签: android


    【解决方案1】:

    不同之处在于,如果您指定的键不存在,optString 将返回空字符串 ("")。另一方面,getString 会引发 JSONException。如果数据丢失是错误的,请使用 getString,如果您不确定它是否存在,请使用 optString。

    查看此链接:https://web.archive.org/web/20150101212410/http://www.json.org/javadoc/org/json/JSONObject.html#optString(java.lang.String)

    【讨论】:

      猜你喜欢
      • 2012-07-04
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-16
      • 2011-04-08
      • 2012-11-24
      • 2013-06-05
      相关资源
      最近更新 更多