如何在Retrofit中提交嵌套请求体?无需新增实体类
解决Retrofit提交嵌套JSON(无需新增实体类)
我懂你的需求——不想为了一层简单的嵌套就额外新建实体类,下面给你两种简洁的实现方式,都能让你提交符合服务端要求的{user:{"username":"asd","password":"123"}}格式:
方法1:用Map动态包装User对象
Retrofit配合Gson转换器可以直接将Map序列化为JSON结构,完美适配嵌套需求:
步骤1:修改接口定义
把原来接收User的@Body参数改成接收Map<String, Object>:
@POST("/test/Logon") Call<Result> getLogon(@Body Map<String, Object> requestBody);
步骤2:构建嵌套请求体
在调用接口时,把User对象放到Map的user键下:
// 初始化你的User对象 User user = new User(); user.username = "asd"; user.password = "123"; // 构建嵌套结构的Map Map<String, Object> requestBody = new HashMap<>(); requestBody.put("user", user); // 发起请求 Call<Result> call = apiService.getLogon(requestBody);
Gson会自动把这个Map序列化为服务端需要的嵌套JSON格式。
方法2:用JsonObject手动构建JSON
如果想更灵活控制JSON结构,可以用Gson的JsonObject来手动拼接:
步骤1:修改接口定义
改成接收JsonObject作为请求体:
@POST("/test/Logon") Call<Result> getLogon(@Body JsonObject requestBody);
步骤2:构建嵌套JSON对象
// 初始化User对象 User user = new User(); user.username = "asd"; user.password = "123"; // 把User转成JsonElement Gson gson = new Gson(); JsonElement userElement = gson.toJsonTree(user); // 构建外层JsonObject JsonObject requestBody = new JsonObject(); requestBody.add("user", userElement); // 发起请求 Call<Result> call = apiService.getLogon(requestBody);
注意事项
确保你的Retrofit实例使用了Gson转换器(这是默认常用的配置):
Retrofit retrofit = new Retrofit.Builder() .baseUrl("你的基础URL") .addConverterFactory(GsonConverterFactory.create()) .build();
这两种方法都不需要新增任何额外的实体类,就能轻松实现服务端要求的嵌套JSON提交啦!
内容的提问来源于stack exchange,提问作者JohnConnor
相关产品推荐
相关产品推荐

