我絕對是Android的初學者。現在我開始學習抽象HTTP請求和響應。我將響應數據綁定到Listview。我正在做這樣的http獲取請求。如何在Android中處理JsonObjectRequest數組和對象集合的響應json Volley
這是我與凌空要求
public class VolleyActivity extends Activity{
private int lastSawFirstListItem;
private int itemLoadedOn;
private ArrayAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.volley_main);
Button getBtn = (Button)findViewById(R.id.btn_get_request);
getBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
ListView listView = (ListView)findViewById(R.id.volleyListView);
adapter = new CustomAdapter(this,new Entity[0]);
listView.setAdapter(adapter);
String url = "http://api.androidhive.info/feed/feed.json";
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject jsonObject) {
List<Entity> items = new ArrayList<Entity>();
try{
jsonObject = jsonObject.getJSONObject("feed");
//Then how to handle my response collection here
//because this is the combination of array and object collection
}
catch (JSONException e)
{
Toast.makeText(getBaseContext(),"JSON exception",Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
Volley.newRequestQueue(getBaseContext()).add(jsonRequest);
}
public Entity convertToEntity(JSONObject item) throws JSONException
{
Entity en = new Entity();
en.setId(item.getInt("id"));
en.setName(item.getString("name"));
en.setName(item.getString("url"));
return en;
}
}
這項活動類的JSON鏈接,我請求http://api.androidhive.info/feed/feed.json
所以請我怎麼處理這個組合?我已經做出拋出錯誤的ArrayRequest。
我處理的響應回調這樣
try{
jsonObject = jsonObject.getJSONObject("feed");
for(int i=0;i<jsonObject.length();i++){
StringBuilder sb = new StringBuilder();
sb.append(i);
String name = jsonObject.getJSONObject(sb.toString()).getString("name");
}
Toast.makeText(getBaseContext(),"ok",Toast.LENGTH_SHORT).show();
}
catch (JSONException e)
{
Toast.makeText(getBaseContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
請發佈錯誤。排隊請求隊列也可以做成一個單例實例。 您可以使用Gson基於POJO進行反序列化。 – TheSunny
這個ObjectRequest不會拋出錯誤。我只是想知道如何遍歷和處理。因爲我從來沒有這樣做過。 –
ArrayRequest將json結果數組作爲錯誤消息拋出。 –