我想通過Volley向我的WCF服務發出GET請求,我想解析它對Java ArrayList
的響應。這裏是我的方法Android Parse Json響應Java ArrayList
public ArrayList<Company> getCompanies(){
String url = AUDITTRACKINGAPP_SERVICE_URI + "GetCompanies";
String tagJsonReq = "companiesRequest";
final ProgressDialog pDialog = new ProgressDialog(context);
pDialog.setMessage("Please Wait...");
pDialog.show();
final ArrayList<Company> companies = new ArrayList<Company>();
JsonObjectRequest companiesRequest = new JsonObjectRequest( Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.v(TAG, "COMPANIES RESPONSE:" + response.toString());
try {
JSONArray companiesJson = response.getJSONArray("GetCompaniesResult");
for (int i = 0; i < companiesJson.length(); i++) {
JSONObject jObject = (JSONObject)companiesJson.get(i);
Company company = new Company();
company.setCompanyId(Integer.parseInt(jObject.getString("CompanyId")));
Log.v(TAG, "COMPANIES setCompanyId:" + jObject.getString("CompanyId"));
company.setCompanyName(jObject.getString("CompanyName"));
Log.v(TAG, "COMPANIES setCompanyName:" + jObject.getString("CompanyName"));
companies.add(company);
}
} catch (JSONException e) {
Log.v(TAG, "COMPANIES RESPONSE ERROR ON PARSING JSON:" + e.getMessage());
}
pDialog.hide();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.v(TAG, "COMPANIES onErrorResponse:" + error.getMessage());
pDialog.hide();
}
});
AppController.getInstance().addToRequestQueue(companiesRequest, tagJsonReq);
return companies;
}
JSON響應:
{"GetCompaniesResult":[{"CompanyId":1,"CompanyName":"CompanyName1"},{"CompanyId":2,"CompanyName":"CompanyName2"}]}
我能夠得到JSON響應,但ArrayList<Company>
返回null。我認爲onResponse
是一個回調方法,並在另一個線程運行,所以我不能填充列表,但因爲我是Android新手我不知道如何管理這個問題。任何幫助,將不勝感激。
你會得到輸出日誌? –
是的,我看到JSON響應@AiyazParmar – Tartar
是你的for循環執行成功嗎? –