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


