java - 如何在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();
}
}
解决方案
为您的请求正文创建 dto 类:
public class UserRequestDTO{ private UserDto user; //getters, setters } public class UserDto{ private String email; private String password; }
使用 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*/));
,并在您的请求中使用它。
推荐阅读
- c# - 检测到布局周期。布局无法完成。检测到布局周期。布局无法完成
- python - Game of Life - 如何通过鼠标点击激活单元格?
- angular7 - 未找到 Angular 7 prod 构建 i18n 文件
- c++ - 使用 LuaBridge 和 C++ 处理 Lua 模块时出错
- bundle - 将多个网络字体捆绑到单个文件
- javascript - 信用卡样式问题
- c - 找到与给定字符串类型数据相同的节点时,我做错了什么?
- sql-server - Service Broker 队列 BROKER_QUEUE_DISABLED 事件触发两次
- javascript - 为什么我必须为常规的“const”变量指定类型,而不是为“for”循环中定义的“const”变量指定类型?
- oracle - 从 sys_refcursor 填充数组