【发布时间】:2014-09-12 11:12:50
【问题描述】:
我正在尝试使用 Volley 库向服务器发出 JSONObject POST 请求,该服务器接受 2 个参数、一个对象(地址)和一个不同对象列表(租户)。
当我尝试发出请求时,第一个参数(地址)在发送前被 Volley 格式化,服务器不接受请求。
我的请求如下所示:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, SERVER_URL,
postPropertyJSONObject, responseListener, errorListener)
我的 postPropertyJSONObject 是这样创建的:
JSONObject obj = new JSONObject();
obj.put("Address", convertAddressToJson(property.getAddress()).toString());
obj.put("Tenants", prop.getTenantList());
convertAddressToJson() 方法如下所示:
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());
我尝试只传入 Address 对象,但这根本没有序列化,所以它也不起作用。我还尝试在请求中使用的 JSONObject 的“地址”字段中传递 Address.toString(),但这也不起作用。
我的 Property 对象的 getAddress() 方法返回一个 Address 对象,看起来像这样:
public class Address {
private String Street;
private String Building;
private String Town;
private String ZipCode;
private String County;
private String Country;
// getters and setters
}
当我在传递请求之前记录地址时,它看起来像这样:
{"Town":"MyTown","Street":"MyStreet","County":"MyCounty","Country":"MyCountry",
"ZipCode":"MyZipCode","Building":"MyBuilding"}
但是当服务器记录它收到的内容时,它看起来像这样:
{\"Town\":\"MyTown\",\"Street\":\"MyStreet\",\"County\":\"MyCounty\",
\"Country\":\"MyCountry\",\"ZipCode\":\"MyZipCode\",\"Building\":\"MyBuilding\"}"
Volley 应用的这种格式似乎改变了我通过请求传递的值,所以谁能告诉我是否有更好的方法来处理这个应该相对简单的任务?我已经使用 String 和 Integer 值向同一台服务器发出请求,但是在尝试将自定义类作为参数传递时遇到了这个问题。
编辑
使用 wbelarmino 的提示,我转而使用哈希图来存储我的自定义对象并从中创建了一个 JSONObject:
HashMap<String, Address> params = new HashMap<String, Address>();
params.put("Address", prop.getAddress());
requestObject = new JSONObject(params);
【问题讨论】:
标签: android json serialization parameters android-volley