Trying to send arraylist to server but it seems the format does not correct.
My params in StringRequest
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("source", "en");
params.put("target", "zh");
JSONArray jsonArray = new JSONArray();
jsonArray.put("hello world");
params.put("stringArray", jsonArray.toString());
return params;
}
My server response
{"result":[],"source":"en","target":"zh","arrayString":"[\"hello world\"]"}
arrayString does not make sense to me because "[\"hello world\"]"
is just a string, not a array of string. I expect the arrayString should be something like this "arrayString":[\"hello world\"]
Any suggestions?
EDIT
Tried to use JsonObjectRequest.
Map<String, Object> params = new HashMap();
params.put("source", "en");
params.put("target", "zh");
params.put("stringArray", Arrays.asList("hello world"));
JSONObject parameters = new JSONObject(params);
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, requestString, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//TODO: handle success
Log.d("successful", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
//TODO: handle failure
}
});
Volley.newRequestQueue(getActivity()).add(jsonRequest);
Server response
successful: {"result":null,"source":null,"target":null,"arrayString":null}
Php code
<?php
$source = $_POST['source'];
$target = $_POST['target'];
$arrayString = $_POST['stringArray'];
echo json_encode(array('result'=>$results,'source'=>$source,'target'=>$target,'arrayString'=>$arrayString));
?>
Edit 2
If I use JSONObject with its put method and JSONArray as well, I still get the null results
JSONObject parameters = new JSONObject();
try {
parameters.put("source", "en");
parameters.put("target", "zh");
JSONArray jsonArray = new JSONArray();
jsonArray.put("hello world");
parameters.put("stringArray", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("JSONParams", parameters.toString());
JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, requestString, parameters, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("successful", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
Print and Server Response
JSONParams: {"source":"en","target":"zh","stringArray":["hello world"]}
successful: {"result":null,"source":null,"target":null,"arrayString":null}