[英]Android Volley how to post array of custom object
I'm new to volley and i need to post an array of custom object to PHP api in order to save it in MYSQL database how can i accomplish this ?我是 volley 的新手,我需要将一组自定义对象发布到 PHP api 以便将其保存在 MYSQL 数据库中,我该如何实现?
Note : I know that my below code will pass only the last object of my array only注意:我知道我下面的代码只会传递我数组的最后一个对象
Here is my object :这是我的对象:
public class object {
String name;
Integer qty;
Integer price;
}
and my code :和我的代码:
final ArrayList<object> myarray = new ArrayList<>();
myarray.add(ob1);
myarray.add(ob2);
RequestQueue queue = Volley.newRequestQueue(this);
JSONObject jsonArray = new JSONObject();
try {
int i = 0;
for (object obj : myarray) {
jsonArray.put("id",i++);
jsonArray.put("name",obj.name);
jsonArray.put("qty",obj.qty);
jsonArray.put("price",obj.price);
}
Log.i("JSON ARRAY ", jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, API_URL, jsonArray, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i("RESPONSE",response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
return params;
}
}; queue.add(request);
}
Need to add your JSONObject
to JSONArray
for every loop like,需要为每个循环将您的JSONObject
添加到JSONArray
,例如,
JSONArray jsonArray = new JSONArray();
int i = 0;
for (object obj : myarray) {
JSONObject jsonObj= new JSONObject();
jsonObj.put("id", i++);
jsonObj.put("name", nameStr);
jsonObj.put("qty", qtyStr);
jsonObj.put("price", priceStr);
jsonArray.put(jsonObj);
}
Log.i("JSON ARRAY ", jsonArray.toString());
this may helps you.这可能对你有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.