今天一同學問我爲什麼JSONOb
ject obj = getJSONObject("data");解析服務器給的數據時報錯:錯誤信息
1:首先看getJSONObject(String string) 源碼
1:首先看getJSONObject(String string) 源碼
/**
* Returns the value mapped by {@code name} if it exists and is a {@code
* JSONObject}.
* @throws JSONException if the mapping doesn't exist or is not a {@code
* JSONObject}.
*/
public JSONObject getJSONObject(String name) throws JSONException {
Object object = get(name);
if (object instanceof JSONObject) {
return (JSONObject) object;
} else {
throw JSON.typeMismatch(name, object, "JSONObject");
}
}
//當返回值不是JSONObject對象時,拋出異常;
2:原因分析
我們就拋出異常了.所以走了else代碼塊,所以我們拿到的不是JSONObject對象
throw JSON.typeMismatch(name, object, "JSONObject");
所以你只能getString();再轉換成JSONObject或者Array;
我們的說法是錯誤的:後臺給你的Json數據
應該這樣說:後臺給你的Json格式的數據字符串