json - Using org.json.JSONObject to accept RequestBody is not working (null value in variable)
问题描述
In a spring boot prj, I am using JSONObject to accept the incomming JSON payload from the client, but the value in userCredentials
is null. How to fix this??
The incoming payload is valid JSON. I checked it.
import org.json.JSONObject;
...
...
@RequestMapping(value="/helloeverybody", method=RequestMethod.POST, consumes="application/json", produces="text/plain")
public ResponseEntity<String> post(@RequestBody JSONObject userCredentials,
HttpServletRequest hsr)
解决方案
我相信使用 aMap
可以解决您的问题。这是一个例子:
@RestController
public static class GenericController {
static final Logger logger = LoggerFactory.getLogger(GenericController.class);
@PostMapping("/generic")
public ResponseEntity<Void> post(@RequestBody Map<String, Object> payload) {
payload.forEach((key, value) -> logger.info("{}={}", key, value));
return ResponseEntity.ok().build();
}
}
我曾经curl
测试过它。
curl -i localhost:8080/generic -d '{"key":"value"}' -H "Content-Type: application/json"
控制台中的响应应该是这样的:
2020-11-27 19:56:57.455 INFO 67478 --- [nio-8080-exec-2] BodyMappingApplication$GenericController : key=value
推荐阅读
- swift - ARKit 绘制带圆角的 3D 纸飞机
- ionic3 - 在日期前 2 天安排本地通知(由用户选择)
- ios - 如何跟踪 TextField 中最后输入的字符?
- ruby - 如何使用 Nokogiri 削减 href
- c# - c# 8 中 switch 表达式的 vb.net 等价物是什么
- django - 如何在 djabgo 中将中间件装饰器用于基于类的视图?
- vba - 4d6 下降最低 VBA
- sql - 大查询 - 将特定字段转换为列
- java - 线程“AWT-EventQueue-0”中的异常 java.lang.StringIndexOutOfBoundsException:开始 0,结束 1,长度 0
- google-chrome-extension - 使用 browser.tabs.executeScript 加载时在选项卡上执行的内容脚本不会触发 window.onload 事件