首页 > 解决方案 > 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)

标签: jsonspring-boot

解决方案


我相信使用 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

推荐阅读