以下是一个示例代码,展示如何使用 Spring Boot 创建一个接收 JSON 参数并返回结果的 POST 接口。

首先,定义一个 User 类,用于接收请求参数:

public class User {
    private String a;
    private String b;
    private String c;

    // getter and setter
}

然后,在控制器中定义一个 POST 接口,接收 User 对象作为参数:

@RestController
@RequestMapping("/api/user")
public class UserController {

    @PostMapping("/adduser")
    public Map<String, Object> addUser(@RequestBody User user) {
        // 处理请求参数,例如将用户信息保存到数据库中

        // 构造返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "添加用户成功");
        return result;
    }
}

在上面的代码中,@PostMapping("/adduser") 表示这是一个 POST 请求,并且路由为 /api/user/adduser@RequestBody User user 表示接收一个 JSON 格式的请求体,并将其转换为 User 对象。

最后,我们可以使用浏览器或者 Postman 工具等发送一条 POST 请求:

POST http://localhost:8080/api/user/adduser
Content-Type: application/json

{
    'a': 'abc',
    'b': '123',
    'c': 'xyz'
}

如果一切正常,会返回以下 JSON 格式的响应:

{
    'code': 0,
    'msg': '添加用户成功'
}
Spring Boot POST 接口:接收 JSON 参数并返回结果

原文地址: https://www.cveoy.top/t/topic/on5w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录