当前位置:主页 > 移动开发 > Android代码 >

JSON中optString和getString方法的区别

时间:2022-10-09 15:33:38 | 栏目:Android代码 | 点击:

optString方法会在对应的key中的值不存在的时候返回一个空字符串,但是getString会抛一个JSONException 。

 /**
   * Returns the value mapped by {@code name} if it exists, coercing it if
   * necessary, or throws if no such mapping exists.
   *
   * @throws JSONException if no such mapping exists.
   */
  public String getString(String name) throws JSONException {
    Object object = get(name);
    String result = JSON.toString(object);
    if (result == null) {
      throw JSON.typeMismatch(name, object, "String");
    }
    return result;
  }
  /**
   * Returns the value mapped by {@code name} if it exists, coercing it if
   * necessary, or the empty string if no such mapping exists.
   */
  public String optString(String name) {
    return optString(name, "");
  }

您可能感兴趣的文章:

相关文章