0

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)
3
  • You don't need to use a JSONObject, you better create your own object containing the payload you're expecting. Commented Nov 27, 2020 at 14:40
  • i can not create any pojos, if you are referring to one. That will result in to lot of pojos in my project and that is not allowed for now. I got to use some generic object like JSONObject and then deal with hashmap conversion. Commented Nov 27, 2020 at 15:13
  • Just use a Map then, something like this will do @RequestBody Map<String, Object> payload Commented Nov 27, 2020 at 18:57

2 Answers 2

1

I tried the same and got the requestBody. The only change was of the package. I used org.json.simple.JSONObject:

import org.json.simple.JSONObject;
...
...

@RequestMapping(value="/helloeverybody", method=RequestMethod.POST, consumes="application/json", produces="text/plain")
public ResponseEntity<String> post(@RequestBody JSONObject userCredentials,
            HttpServletRequest hsr)
Sign up to request clarification or add additional context in comments.

Comments

0

I do believe that using a Map will solve your problem. Here's an example:

@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();
    }
}

I have used curl to test it.

curl -i localhost:8080/generic -d '{"key":"value"}' -H "Content-Type: application/json"

The response in the console should be something like:

2020-11-27 19:56:57.455  INFO 67478 --- [nio-8080-exec-2] BodyMappingApplication$GenericController : key=value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.