我想创建一个搜索我的Android应用程序,但当我尝试我只是获得JSON值... JSON对象无法转换为JSONArray。顺便说一下,我正在使用Volley。
获取JSON的代码示例:
private void getData() {
String id = editTextId.getText().toString().trim();
if (id.equals("")) {
Toast.makeText(this, R.string.i_enter_request, Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,getString(R.string.d_wait),getString(R.string.d_fetch),false,false);
String url = AppConfig.DATA_URL+editTextId.getText().toString().trim();
JsonArrayRequest searchReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
Toast.makeText(getApplicationContext(), "Response: " + response.toString(), Toast.LENGTH_LONG).show();
loading.dismiss();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject pObj = response.getJSONObject(i);
Products item = new Products();
item.setTitle(pObj.getString("name"));
ProductItems.add(item);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
loading.dismiss();
}
});
AppController.getInstance().addToRequestQueue(searchReq);
}
通过搜索“1”来获取JSON:
{
products: [
{
id: "1",
name: "Test",
price: "123",
item_desc: "Its a Test"
}],
success: 1
}
如果有人可以帮助我,那就太好了。 谢谢
答案 0 :(得分:0)
这不是JSONArray:
{products:[{id: "1", name: "Test", price: "123", item_desc: "Its a Test" } ], success: 1 }
因此您收到错误是因为您的回调尝试将其作为JSONArray
传入您需要将回调更改为:
@Override
public void onResponse(JSONObject response) {}
然后你需要将响应解析为JSONObject,而不是JSONArray。