marcode_ely
marcode_ely

Reputation: 436

Android Volley POST - JSON Encoding in body

I'm using Volley Android for POST some data to a Restful Api endpoint, using postman it works great body data in raw and application/json e.g:

{
    "operation": "someaction",
    "key": "pk_test_fssdfsdfjkhkjsdhf84334",
    "token": "tk_test_432332sdxxaJJJJHHHshhsas",
    "ssids":[[{
        "mac":"34:15:13:d4:59:f1" //<--this is important here, it's mac addr
            }]] //<-- yup, with double double [[ ... ]]
}

It works using POSTMAN and returns enter image description here

The issue starts when I use volley in the code below:

public void getBleeCardData(Response.Listener<String> response, final String ssidsdata, final ProgressDialog pd)throws JSONException {

    String url = "https://www......com/api/something.do";

    JSONObject jsonBody = new JSONObject();
               jsonBody.put("operation", "something");
               jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
               jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
               jsonBody.put("ssids", ssidsdata.toLowerCase()); 

    final String mRequestBody = jsonBody.toString();

    RequestQueue queue = Volley.newRequestQueue(context);
    StringRequest postRequest = new StringRequest(Request.Method.POST, url,new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d("Response", response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("ERROR", "error => " + error.toString());
                }
            }
    ) {
        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                return null;
            }
        }

        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }
    };
    queue.add(postRequest.setRetryPolicy(new DefaultRetryPolicy(30000,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT))); }

I need help with the encoding, using Volley the data sent like:

{"operation":"dataMachines","key":"pk_test_6pRNAHGGoqiwFHFKjkj4XMrh","token":"tk_test_ZQokik736473jklWgH4olfk2","ssids":"[[{\"mac\":\"34:15:13:d4:59:f1\"}]]"}

Why is sending this node like "ssids":"[[{\"mac\":\"34:15:13:d4:59:f1\"}]]"}like this?, What about the "\", some special encoding to remove it?

Is possible change the encoding to prevent those "\"?

Upvotes: 1

Views: 2122

Answers (3)

D.J
D.J

Reputation: 1559

JSONObject obmacAdd=new JSONObject();
JSONArray array=new JSONArray();
obmacAdd.put("mac","34:15:13:d4:59:f1");
array.put(obmacAdd.toString());

now

jsonBody.put("ssids", array.toString()); 

Upvotes: 0

Mushirih
Mushirih

Reputation: 451

According to the android code,the below expects a string,while you are parsing an object:

 jsonBody.put("ssids", ssidsdata.toLowerCase()); 

You could make the ssid seperately then add it in the json body like this:

JSONObject ssid= new JSONObject();
ssid.put("mac":"34:15:13:d4:59:f1");
ssid.put("key2","Value2");

The add the ssid object into your Json object to send:

    JSONObject jsonBody = new JSONObject();
    jsonBody.put("operation", "something");
     jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
   jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
  jsonBody.put("ssids", ssid); 

As well explaned here: Pass an object containing key value pairs, as a value to a hashmap in Java/Android

Upvotes: 0

Kunu
Kunu

Reputation: 5134

Create a JsonObjectRequest

JSONObject jsonBody = new JSONObject();
           jsonBody.put("operation", "something");
           jsonBody.put("key", "pk_try_oqiwFHFKjkj4XMrh");
           jsonBody.put("token", "tk_tkn_erwweelWgH4olfk2");
           jsonBody.put("ssids", ssidsdata.toLowerCase()); 

JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jsonBody,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                //Log.d("Responses", jsonObject.toString());
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                //Log.e("responses", volleyError.toString());
            }
        });

if you are sending JSONArray then instead of JsonObjectRequest use JsonArrayRequest

Upvotes: 1

Related Questions