0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

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.