首页 > 解决方案 > 如何在android中发送嵌套的json作为帖子

问题描述

我正在使用 android valley 库,目前我只能发布简单的 json,我正在努力发布这样的嵌套 json 格式:

{
"user": {
    "email": "digest@example.com",
    "password": "thedigest123" 

看起来我不知道如何格式化这种情况下的嵌套 json,你能帮我吗?

这是我用来连接我的 web api 的 java 类

public void login(String email, String password) {
    String url = BASE_URL + "api/session";
    JSONObject jsonObject = new JSONObject();

    try {
        jsonObject.put("email", email);
        jsonObject.put("password", password);

        Response.Listener<JSONObject> successListener = new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Toast.makeText(mApplication, "Success", Toast.LENGTH_SHORT).show();
            }
        };

        Response.ErrorListener errorListener = new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(mApplication, "Error", Toast.LENGTH_SHORT).show();
            }
        };

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, successListener, errorListener);
        mRequestQueue.add(request);
    }

    catch (JSONException e) {
        Toast.makeText(mApplication, "JSON exception", Toast.LENGTH_SHORT).show();
    }

}

标签: javaandroidjsonapiandroid-volley

解决方案


  1. 为您的请求正文创建 dto 类:

    public class UserRequestDTO{
        private UserDto user;
        //getters, setters
    }
    public class UserDto{
        private String email;
        private String password;
    }
    
  1. 使用 Gson lib 将其转换为 json 字符串:

    public static String stringify(Object obj) {
         Gson gson = new Gson();
         String jsonString = gson.toJson(obj);
         return jsonString;
    }
    

然后将其转换为 StringEntity withnew StringEntity(stringify(new UserRequestDto(/*params*/), "UTF-8"); 或 JSONObject with new JSONObject(stringify(new UserRequestDto(/*params*/));,并在您的请求中使用它。


推荐阅读