Reputation: 1893
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?
Upvotes: 1
Views: 2861
Reputation: 909
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.
}
Upvotes: 0
Reputation: 352
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.
Upvotes: 1
Reputation: 7330
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();
Upvotes: 3