我有一個JSON檢索數據庫的所有用戶。爲了簡化,我將顯示前兩個用戶:如何在Android上使用Volley檢索沒有名稱的JSON?
[
{
"id":"1",
"name":"Peter",
"age":"25"
},
{
"id":"2",
"name":"Andrew",
"age":"32"
},
...
]
正如你所看到的,它是沒有名字的,它包含了一些JSONObjects
所以我試圖用Volley
庫經歷了整個檢索Android
這些數據的數組陣列但沒有成功。
下面是我得到的時刻代碼:
RequestQueue queue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try{
if (response != null) {
for(int i = 0; i < response.length(); i++){
JSONObject obj = response.getJSONObject(i);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("LOG", error.toString());
}
});
queue.add(jsonArrayRequest);
它總是給我下面的錯誤:
Unhandled exception: org.json.JSONException
我也試圖嘗試檢索之前檢索JSONArray
JSONObject
但它不允許我,因爲方法
JSONArray json = response.getJSONArray(0);
也給了我以前指出的同樣的錯誤。
我找了很多例子,我看不出我的問題在哪裏。
我在做什麼錯?
在此先感謝!
您確定您的服務器響應格式正確嗎?我嘗試了你的面向JSON的代碼部分(硬編碼你輸入的字符串)並且我無法重現你得到的錯誤 –
@GaëtanMaisse在我執行代碼之前,Android Studio給了我那個錯誤,所以我認爲問題是關於代碼的。 –
@ Error404您的代碼執行得很好。你的應用程序只是崩潰,因爲你正在解析(或獲取)JSON不正確。但是,正如第一條評論所述,您的數據必須無效,因爲我們無法重現您的錯誤。 –