简体   繁体   中英

how to retrieve a value from json in spring boot in post request

Hi I am trying to follow this article to consume a json file to retrieve a value from it and do some processing on it: https://www.baeldung.com/spring-boot-json

I am following this github repo and students folder: https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students

the thing is in post mapping in StudentController.java , I saw this:

    @PostMapping("/")
    public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
        Student createdStudent = service.create(student);

        URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
            .path("/{id}")
            .buildAndExpand(createdStudent.getId())
            .toUri();

        return ResponseEntity.created(uri)
            .body(createdStudent);

    }

He's passing student object in @RequestBody , what if I need to extract a value from a json, like this post request is receiving for example json like this:

{'key':'val1',
'key2':'val2'
}

and in my spring boot app I need to retrieve this json object and get to do some processing on 'val1', which should be retrieved something like this object['key'], I am not sure how to do so? can u please help me in this?

I did not completely get what you are trying to do but if i'm correct, you are trying to retrieve a request body manually and do some business on it. To do that:

public ResponseEntity<?> login(HttpServletRequest request) {
    String body = request.getReader().lines().collect(Collectors.joining(System.lineSeperator()));

    ObjectMapper mapper = new JsonMapper();
    JsonNode json = mapper.readTree(body);

    String email = json.get("email").asText();
    String password = json.get("password").asText();

    ...
}

this is a code sample from another project, i hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM