JSON数据格式: 我试图获取这个数组json数据,但没有得到它。
[{"Items":"Chicken Burger","Price":"250","Quantity":"2"},
{"Items":"Hamburger","Price":"230","Quantity":"3"}]
MyCartActivity类: 我尝试使用Volley,我现在得到JSONArray无法转换为JSONObject错误。你能提一下改变的地方,以便我可以得到我的数据吗?
final JsonObjectRequest request = new JsonObjectRequest (Request.Method.POST, fetchurl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i=0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String Price = object.getString("Price");
String Name = object.getString("Items");
String Quantity = object.getString("Quantity");
adapter = new CartAdapter(MyCartActivity.this, list);
list.add(new CartPojo(Price, Name, Quantity));
adapter.notifyDataSetChanged();
progressbar.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
适配器类:
public CartAdapter(Activity activity, List datalist) {
this.activity = activity;
this.datalist = datalist;
}
@Override
public int getCount() {
return datalist.size();
}
@Override
public Object getItem(int position) {
return datalist.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.cart_item_layout, null);
TextView ItemName = convertView.findViewById(R.id.item_name);
TextView Price = convertView.findViewById(R.id.item_price);
TextView Quantity = convertView.findViewById(R.id.items_quantity);
CartPojo pojo = datalist.get(position);
ItemName.setText(String.valueOf(pojo.getName()));
Price.setText(String.valueOf(pojo.getPrice()));
Quantity.setText(String.valueOf(pojo.getQuantity()));
return convertView;
}
请给我一些解决方案......
答案 0 :(得分:0)
无法将响应解析为JSONObject
,因为它不是,而是JSONArray
。您可以发送一个简单的StringRequest
,然后使用JSONArray
构造函数将响应字符串解析为JSONArray(response)
。
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONArray arr = new JSONArray(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
或使用JsonArrayRequest
。 Here's一个例子。