SpringBoot 如何同时接收JSONObject和参数呢?
下文笔者讲述SpringBoot开发Controller时,同时接收JSONObject和参数的方法分享,如下所示
SpringBoot接收JSONObject和参数信息的实现思路:
方式1:
借助@RequestBody和@RequestParam注解
即可实现同时接收JSONObject和参数信息
方式2:
借助ObjectMapper()对象从request中获取
和request.getParameter()方法
即可同时获取JSONObject和参数信息
例:同时获取JSONObject和参数的示例
使用@RequestBody和@RequestParam注解
@PostMapping(value = "/api/test")
public ResponseEntity<Void> receiveData(@RequestBody JSONObject data, @RequestParam("param1") String param1) {
// 处理数据
return ResponseEntity.ok().build();
}
使用HttpServletRequest
@PostMapping(value = "/api/test")
public ResponseEntity<Void> receiveData(HttpServletRequest request) {
try {
JSONObject data = new ObjectMapper().readValue(request.getInputStream(), JSONObject.class);
String param1 = request.getParameter("param1");
// 处理数据
return ResponseEntity.ok().build();
} catch (IOException e) {
// 处理异常
return ResponseEntity.badRequest().build();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


