How do I make a Volley JSONObject Request with a custom object as a parameter?
Asked Answered
T

2

10

I'm trying to make a JSONObject POST request using the Volley library to a server which takes 2 parameters, an object (Address) and a list of different objects (Tenants).

When I try to make the request, the first parameter (Address) is formatted by Volley before it is sent and the request is not accepted by the server.

My request looks something like this:

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, SERVER_URL,
    postPropertyJSONObject, responseListener, errorListener)

My postPropertyJSONObject is created like this:

JSONObject obj = new JSONObject();
obj.put("Address", convertAddressToJson(property.getAddress()).toString());
obj.put("Tenants", prop.getTenantList());

The convertAddressToJson() method looks like this:

JSONObject jsonObject= new JSONObject();
jsonObject.put("Building", address.getBuilding());
jsonObject.put("Street", address.getStreet());
jsonObject.put("Town", address.getTown());
jsonObject.put("ZipCode", address.getZipCode());
jsonObject.put("County", address.getCounty());
jsonObject.put("Country", address.getCountry());

I tried just passing in the Address object but this wasn't serialized at all so it didn't work either. I also tried just passing Address.toString() in the "Address" field of the JSONObject used in the request but that didn't work either.

The getAddress() method of my Property object returns an Address object which looks something like this:

public class Address {

    private String Street;
    private String Building;
    private String Town;
    private String ZipCode;
    private String County;
    private String Country;
    // getters and setters
}

When I Log the address before I pass it the the request it looks like this:

{"Town":"MyTown","Street":"MyStreet","County":"MyCounty","Country":"MyCountry",
 "ZipCode":"MyZipCode","Building":"MyBuilding"}

But when the server Logs what it has received, it looks like this:

{\"Town\":\"MyTown\",\"Street\":\"MyStreet\",\"County\":\"MyCounty\",
 \"Country\":\"MyCountry\",\"ZipCode\":\"MyZipCode\",\"Building\":\"MyBuilding\"}"

This formatting applied by Volley seems to be altering the value I pass with my request so can anyone tell me if there's a better way to approach this task that should be relatively straightforward? I've made requests to the same server using String and Integer values but I've had this problem while trying to pass a custom class as parameter.

EDIT

Using wbelarmino's tip, I switched to using a hashmap to store my custom object and created a JSONObject from that:

HashMap<String, Address> params = new HashMap<String, Address>();
params.put("Address", prop.getAddress());
requestObject = new JSONObject(params);
Turin answered 21/7, 2014 at 20:5 Comment(0)
C
19

You can try this:

final String URL = "/volley/resource/12";

Post params to be sent to the server

HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
   @Override
   public void onResponse(JSONObject response) {
       try {
           VolleyLog.v("Response:%n %s", response.toString(4));
       } catch (JSONException e) {
           e.printStackTrace();
       }
   }
}, new Response.ErrorListener() {
   @Override
   public void onErrorResponse(VolleyError error) {
       VolleyLog.e("Error: ", error.getMessage());
   }
});

See more Http requests in android usingvolley

Cioffi answered 21/7, 2014 at 20:17 Comment(4)
Using a hashmap solved this issue for me. Thank you!Turin
Solveda issue,why JSON Object with with put cant be taken as post params,in my earlier porject with php post service it workedCocci
What if we don't need a Hashmap and we just want a single String from the JSON response? Does this apply to that? What syntax difference would it have?Treponema
Thank you, my friend.Uncanny
E
0
 final RequestQueue requestQueue = Volley.newRequestQueue(this);
    final String url ="http://mykulwstc000006.kul/Services/Customer/Register";
    Map<String, String>  params = new HashMap<String, String>();
    params.put("MobileNumber", "+97333765439");
    params.put("EmailAddress", "[email protected]");
    params.put("FirstName", "Danish2");
    params.put("LastName", "Hussain2");
    params.put("Country", "BH");
    params.put("Language", "EN");
    JsonObjectRequest req = new JsonObjectRequest(url, new JSONObject(params),
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {
                        VolleyLog.v("Response:%n %s", response.toString(4));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    }){
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            String username ="[email protected]";
            String password = "elie73";

            String auth =new String(username + ":" + password);
            byte[] data = auth.getBytes();
            String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Authorization","Basic "+base64);
            return headers;
        }

    };
    requestQueue.add(req);
}
Eberto answered 5/4, 2018 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.