【问题标题】:How do I make a Volley JSONObject Request with a custom object as a parameter?如何使用自定义对象作为参数发出 Volley JSONObject 请求?
【发布时间】: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


    【解决方案1】:

    你可以试试这个:

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

    发送参数到服务器

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

    查看更多Http requests in android usingvolley

    【讨论】:

    • 使用哈希图为我解决了这个问题。谢谢!
    • 已解决问题,为什么 JSON 对象与 put 不能被视为 post 参数,在我早期的 php post 服务项目中它有效
    • 如果我们不需要 Hashmap 而只需要 JSON 响应中的单个字符串怎么办?这适用于那个吗?它会有什么语法差异?
    • 谢谢你,我的朋友。
    【解决方案2】:
     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", "danish.hussain4@das.com");
        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 ="eli@gmail.com";
                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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-26
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多