PalBo
PalBo

Reputation: 2612

Receive POST request and obtain JSON elements in Java/Spring

So I have followed the Spring guide below to build a simple rest service. https://spring.io/guides/gs/rest-service/

At the moment I can use Postman to get some values using a GET request to the URL http://localhost:8080/greeting

I now want to change this to a POST request and send some JSON structure from Postman to my controller, and also obtain the elements sent from Postman and for example, print them in my console. My controller code looks like this:

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";
    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(), String.format(template, name));
    }
}

Let's say I want to post the JSON structure:

{
  "header": {"name": "1234"},
  "address": "someplace"
}

How would I go about retrieving and printing the address element in my Java code?

Upvotes: 0

Views: 141

Answers (2)

benson micheal
benson micheal

Reputation: 1

If you have payload that changes depends on the requirement you can use a Map instead of a POJO class.

@RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String greeting(HashMap<String,Object> payload){
....
....
}

Upvotes: 0

Marc Stroebel
Marc Stroebel

Reputation: 2357

Just create a pojo for your request data like

public class RequestData {
    Map<String,String> header;
    String address;
}

and a controller method

@PostMapping("/request")
public ResponseEntity postController(
  @RequestBody RequestData requestData) {

    System.out.println(requestData.address)
    return ResponseEntity.ok(HttpStatus.OK);
}

Upvotes: 2

Related Questions