文章出處
文章列表
Json解析的時候有兩種方式根據Key的值獲取對應的Value:
一種是get,一種是opt:,
先看optInt的源碼:
public int optInt(int index) { return optInt(index, 0); } /** * Returns the value at {@code index} if it exists and is an int or * can be coerced to an int. Returns {@code fallback} otherwise. */ public int optInt(int index, int fallback) { Object object = opt(index); Integer result = JSON.toInteger(object); return result != null ? result : fallback; }
主要是看有兩個參數的方法,當根據當找不到當前給的key的時候,會使用fallback中的值作為value返回。
下面是getInt的源碼:
public int getInt(String name) throws JSONException { Object object = get(name); Integer result = JSON.toInteger(object); if (result == null) { throw JSON.typeMismatch(name, object, "int"); } return result; }
getInt方法在找不到對應的key的時候會拋異常。
文章列表
全站熱搜