Android volley 更改我对 JsonObjectRequest 的响应

Android volley change my response from JsonObjectRequest

我正在尝试使用 volley 库制作一个标准的 JsonObjectRequest。除了请求的响应外,一切正常。

我是这样处理请求的:

JSONObject jsonObject = new JSONObject();
jsonObject.put("geoLong", location.getLongitude());
jsonObject.put("geoLat", location.getLatitude());

JsonObjectRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, url,
                    jsonObject.toString(), createResponseListener(), createErrorListener()); 
jsonRequest.setRetryPolicy(new DefaultRetryPolicy(15000, 2, 1));

requestQueue.add(jsonRequest);

我期待以下 json 响应:

{
"total": 79,
"results": [
{
  "id": "123",
  "title": "test",
  "distance": 3873.7552258171,
  "address": {
    "street": "Street",
    "zip": "12345",
    "city": "city",
    "country": "country",
  },
  "geo": {
    "longitude": x,
    "latitude": y
  }
}, 

...
...

]}

但是从我的 Volley Request 中我得到了这样的信息:

{
"nameValuePairs": {
"total": 79,
"results": {
  "values": [{
  "nameValuePairs": {
    "id": 123, 
    "title": "test", 
    "distance": 3873.7552258171, 
    "address": {
      "nameValuePairs": {
        "street": "street", 
        "zip": "zip", 
        "city": "city", 
        "country": "country"
      }
    },
    "geo": {
      "nameValuePairs": {
        "longitude": x, 
        "latitude": y
      }
    }
  },

... 
...

}]}}

有谁知道为什么响应的格式是这样的,我怎样才能将其更改为我期望的格式?

试试这个。使用 HashMap 在 Post 个请求中发送参数

HashMap<String,String> params = new HashMap<>();
params.put("geoLong", location.getLongitude());
params.put("geoLat", location.getLatitude());

然后

JsonObjectRequest jsonRequest = new JsonObjectRequest(url,
                    new JSONObject(params), createResponseListener(), createErrorListener());

为了更好地理解检查这个代码片段,我在发出 post 请求时使用了它,并且我得到了预期的响应。

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

我自己想出来的。我将 JSON 作为字符串发送到第二个 activity,我正在使用

new Gson().toJson(response)

将 JSON 对象更改为字符串,这改变了 JSON 格式。 我不知道为什么会这样,但这就是问题所在。