1

I am building an API and do a POST-request with the following method:

public ResponseEntity<ProjectRequest> createProject(ProjectRequest project) {
        ProjectResponse projectResponse = new ProjectResponse();
        PersonMember personMember = new PersonMember();

        String personResponse = restTemplate.postForObject(PERSON_URL, project.getPersonMember(), String.class);

        System.out.println(personResponse);
        return new ResponseEntity<ProjectRequest>(HttpStatus.CREATED);
    }

However, it is inconvenient to work with personResponse as a String, because I can not easily extract values from the response Such as personID, firstName and etc.

What is a good way to work with the key/value pairs when using responseEntity?

2
  • Can you show us the value of personResponse? Commented Dec 4, 2019 at 7:49
  • You shouldn't perform the JSON serialisation yourself. Let SpringBoot do that for you as it instantiates an Jackson ObjectMapper. For that serialisation to be perform, you would need to add the entity you want SpringBoot to serialize as an entity of your ResponseEntity Commented Dec 4, 2019 at 7:52

3 Answers 3

3

You should leave this work to Spring.

Create some kind of PersonDto

public class PersonDto {
    private String firstName;
    private String lastName;
    //etc.

    //getters and setters

}

And then map the response to this PersonDto as:

ResponseEntity<PresonDto> response = restTemplate
                    .postForEntity(PERSON_URL, project.getPersonMember(), PersonDto.class);
PersonDto presonDto = response.getBody();
Sign up to request clarification or add additional context in comments.

Comments

1

This might help :

Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"

Using anotations ( @ResponseBody ResponseEntity ) and using a JSON as an object for your response might answer your question.

Comments

0

Whenever you pass a POJO to the ResponseEntity, Spring converts it to a Json. So try to create a POJO for your PersonResponse(If it isn't a POJO already) and pass the object directly to ResponseEntity. It should look like this:

class PersonResponse{
long id;
String name;
String description;

//Getters and setters for the fields.
}

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.