Simple JSON parsing not working in POST to Spring API

59 views Asked by At

I've defined a simple API with a JSON object called Foo in the request body:

@PostMapping(value = "/foo", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Foo> foo(@RequestBody Foo request) {
    log.info("request:{}", request);
    log.info("request.id:{}", request.getId());
    return new ResponseEntity<Foo>(request, HttpStatus.OK);
}

Here is the Foo class definition:

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
public class Foo {
    String id;
}
    

Here is the curl script:

curl --location 'localhost:8080/notification-api/foo' \
--header 'Content-Type: application/json' \
--data '{"id":"a string"}'

But the requst.id value is always null from within the foo() method when the curl script is called.

1

There are 1 answers

0
paiego On

Thanks @KyreX ... if you post an answer I'll accept it.

The problem was that the RequestBody came from the wrong import:

*import io.swagger.v3.oas.annotations.parameters.RequestBody;*

rather than:

*import org.springframework.web.bind.annotation.RequestBody;*