How to grab integer value from JSON input in spring?

In my spring project, I get all input values ​​in JSON format.

@ResponseBody UserDto userDto

Abstract ResponseBodyis good for capturing data. But how can I achieve something as follows?

@ResponseBody String userId;

When writing the above code, userId does not receive. Is there any other annotation to capture a single value without using a wrapper? or can I create custom functionality myself to achieve this?

Any suggestions would be helpful.

+4
source share
1 answer

You can use this approach as is, you just need to change your input:

@SpringBootApplication
public class So45583717Application {

    public static void main(String[] args) {
        SpringApplication.run(So45583717Application.class, args);
    }

    @RestController
    @RequestMapping("/")
    public static class Ctrl {

        @PostMapping
        public String post(@RequestBody Integer userId) {
            return "UserId is: " + userId;
        }
    }
}

Example:

curl -XPOST 'localhost:8080' -H'Content-Type: application/json' -d'42'
UserId is: 42%

- { "userId": 42 }, -, .

- :

@RestController
@RequestMapping("/")
public static class Ctrl {
    private final ObjectMapper mapper = new ObjectMapper();

    @PostMapping
    public String post(@RequestBody String body) throws IOException {
        final JsonNode jsonNode = mapper.readTree(body);
        return "UserId is: " + jsonNode.findValue("userId");
    }
}

:

curl -XPOST 'localhost:8080' -H'Content-Type: application/json' -d'{"userId": 42}'
UserId is: 42% 
+4

Source: https://habr.com/ru/post/1683310/


All Articles