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);