Я хочу отправить данные json на сервер.
final JSONObject root = new JSONObject();
Integer i = 0;
for(Cart_Product cart_product : cartArraylist)
{
final String title = cart_product.getTitle();
final Double price = cart_product.getPrice();
final Integer quantity= cart_product.getCountvalue();
try {
root.put("id",i);
root.put("title",title);
root.put("price",price);
root.put("quantity",q);
i++;
} catch (JSONException e) {
e.printStackTrace();
}
}
Map<String, String> postParam= new HashMap<String, String>();
postParam.put("un", root.toString());
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
Constants.URL_ORDER, new JSONObject(postParam),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObject = new JSONObject(response.toString());
Toast.makeText(getApplicationContext(),
jsonObject.getString("message"),
Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
MySingleton.getInstance(this).addToRequestQueue(jsonObjReq);
}
}
И вот мой php-код:
$body = file_get_contents('php://input');
$postvars = json_decode($body,true);
$user = $postvars['un'];
$pass = $postvars['p'];
$response['message']=$user;
echo json_encode($response);
Этот оператор эха показывает последнюю строку данных типа (id:5, title:val,price: val, quantity = val )
. Я хочу получить доступ по одному к каждой строке.
ИЛИ, пожалуйста, предложите любую другую технику для размещения данных json.
Благодарю.
Вы переписываете свои данные и передаете только последнее необработанное серверу. Вы должны взять JsonArray для хранения всех данных
JSONArray arrayRoot=new JSONArray();
Integer i = 0;
for(Cart_Product cart_product : cartArraylist)
{
final JSONObject root = new JSONObject();
final String title = cart_product.getTitle();
final Double price = cart_product.getPrice();
final Integer quantity= cart_product.getCountvalue();
try {
root.put("id",i);
root.put("title",title);
root.put("price",price);
root.put("quantity",q);
arrayRoot.put(i,root );//add JSONObject to array
i++;
} catch (JSONException e) {
e.printStackTrace();
}
}
postParam.put("un", arrayRoot.toString());