Aid*_*ido 10 parameters serialization android json android-volley
我正在尝试使用Volley库将JSONObject POST请求发送到服务器,该服务器接受2个参数,一个对象(地址)和一个不同对象列表(租户).
当我尝试发出请求时,第一个参数(地址)在发送之前由Volley格式化,并且服务器不接受该请求.
我的请求看起来像这样:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, SERVER_URL,
postPropertyJSONObject, responseListener, errorListener)
Run Code Online (Sandbox Code Playgroud)
我的postPropertyJSONObject是这样创建的:
JSONObject obj = new JSONObject();
obj.put("Address", convertAddressToJson(property.getAddress()).toString());
obj.put("Tenants", prop.getTenantList());
Run Code Online (Sandbox Code Playgroud)
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());
Run Code Online (Sandbox Code Playgroud)
我试过传递Address对象,但这根本没有序列化,所以它也不起作用.我还尝试在请求中使用的JSONObject的"Address"字段中传递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
}
Run Code Online (Sandbox Code Playgroud)
当我在传递地址之前记录地址时,请求看起来像这样:
{"Town":"MyTown","Street":"MyStreet","County":"MyCounty","Country":"MyCountry",
"ZipCode":"MyZipCode","Building":"MyBuilding"}
Run Code Online (Sandbox Code Playgroud)
但是当服务器记录它收到的内容时,它看起来像这样:
{\"Town\":\"MyTown\",\"Street\":\"MyStreet\",\"County\":\"MyCounty\",
\"Country\":\"MyCountry\",\"ZipCode\":\"MyZipCode\",\"Building\":\"MyBuilding\"}"
Run Code Online (Sandbox Code Playgroud)
Volley应用的这种格式似乎正在改变我通过我的请求传递的价值所以任何人都可以告诉我是否有更好的方法来处理这个应该相对简单的任务?我使用String和Integer值向同一服务器发出了请求,但在尝试将自定义类作为参数传递时遇到了这个问题.
编辑
使用wbelarmino的提示,我切换到使用hashmap存储我的自定义对象并从中创建了一个JSONObject:
HashMap<String, Address> params = new HashMap<String, Address>();
params.put("Address", prop.getAddress());
requestObject = new JSONObject(params);
Run Code Online (Sandbox Code Playgroud)
wbe*_*ino 17
你可以试试这个:
final String URL = "/volley/resource/12";
Run Code Online (Sandbox Code Playgroud)
发布params以发送到服务器
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());
}
});
Run Code Online (Sandbox Code Playgroud)
在android usingvolley中查看更多Http请求
| 归档时间: |
|
| 查看次数: |
38444 次 |
| 最近记录: |