【问题标题】:How to send nested json as post in android如何在android中发送嵌套的json作为帖子
【发布时间】:2020-11-28 18:34:31
【问题描述】:

我正在使用 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();
    }

}

【问题讨论】:

    标签: java android json api android-volley


    【解决方案1】:
    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;
      }
      

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

    【讨论】:

    • 这将是明智的选择,特别是如果有更复杂的JSONObjects。 +1
    【解决方案2】:

    如果您不想要 Gson 的开销或创建类(除非您打算拥有更复杂的对象),您可以简单地这样做:

    JSONObject userJsonObject = new JSONObject("{ \"user\": {\"email\": \"" + email + "\", \"password\": \"" + password + "\" } }");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2013-06-03
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多