在Spring Boot中,可以使用@RequestBody注解来接收JSON参数。
例如,假设有一个POST请求,请求体是一个JSON对象,包含name和age两个字段,可以按照以下步骤来接收JSON参数:
@RequestBody注解来接收JSON参数:@PostMapping("/example")
public void handleRequest(@RequestBody ExampleRequest request) {
// 处理请求
}
public class ExampleRequest {
private String name;
private int age;
// 省略getter和setter方法
}
这样,当收到HTTP请求时,Spring Boot会将请求体中的JSON数据转换为ExampleRequest对象,并自动绑定到handleRequest方法的参数上。
注意:
需要确保请求的Content-Type是application/json,否则Spring Boot无法正确解析请求体。
需要在pom.xml文件中添加相应的依赖,以支持JSON转换功能。可以使用jackson-databind库或其他JSON转换库。
另外,还可以使用@RestController注解来简化代码,它相当于@Controller和@ResponseBody的组合。使用@RestController注解后,方法的返回值会自动转换为JSON格式的响应。例如:
@RestController
public class ExampleController {
@PostMapping("/example")
public ExampleResponse handleRequest(@RequestBody ExampleRequest request) {
// 处理请求
ExampleResponse response = new ExampleResponse();
// 设置响应数据
return response;
}
}
这样,handleRequest方法的返回值会自动转换为JSON格式的响应返回给客户端。