Android 如何使用自定义对象作为参数发出 Volley JSONObject 请求?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24873718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:52:52  来源:igfitidea点击:

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

androidjsonserializationparametersandroid-volley

提问by Aido

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

我正在尝试使用 Volley 库向服务器发出 JSONObject POST 请求,该请求带有 2 个参数、一个对象(地址)和一个不同对象(租户)的列表。

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.

当我尝试发出请求时,第一个参数(地址)在发送之前由 Volley 格式化,并且服务器不接受请求。

My request looks something like this:

我的请求看起来像这样:

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

My postPropertyJSONObject is created like this:

我的 postPropertyJSONObject 是这样创建的:

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

The convertAddressToJson() method looks like this:

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

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.

我尝试只传入 Address 对象,但这根本没有序列化,因此它也不起作用。我还尝试在请求中使用的 JSONObject 的“地址”字段中传递 Address.toString() ,但这也不起作用。

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

我的 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
}

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.

Volley 应用的这种格式似乎正在改变我通过我的请求传递的值,所以有人能告诉我是否有更好的方法来处理这个应该相对简单的任务?我已经使用 String 和 Integer 值向同一台服务器发出请求,但是在尝试将自定义类作为参数传递时遇到了这个问题。

EDIT

编辑

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

使用 wbelarmino 的提示,我切换到使用哈希图来存储我的自定义对象并从中创建一个 JSONObject:

HashMap<String, Address> params = new HashMap<String, Address>();
params.put("Address", prop.getAddress());
requestObject = new JSONObject(params);

回答by wbelarmino

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

在 android usingvolley 中查看更多Http 请求

回答by Syed Danish Haider

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