Reputation: 8550
According to this question, my method should be sending a JSON object via Jackson:
Returning JSON object as response in Spring Boot
But I am receiving a string at the client.
Here's the relevant parts:
@CrossOrigin(origins = "*")
@RestController
public class AuthController {
@PostMapping("/api/signup")
public String signup(HttpServletRequest request, HttpServletResponse response){
return "{'status':'fail', 'message':'foo'}";
}
}
Upvotes: 1
Views: 2486
Reputation: 1472
While you were right about single quotes, you can achieve the JSON response without using DTO if you don't want to. You can try this:
@PostMapping("/api/signup")
public ResponseEntity signup(HttpServletRequest request, HttpServletResponse response) {
return ResponseEntity
.status(<http_status>)
.contentType(MediaType.APPLICATION_JSON)
.body("{\"status\":\"fail\", \"message\":\"foo\"}");
}
Upvotes: 3
Reputation: 1672
You explicitly say return "some string";
so it does what you asked for.
Instead, you should construct an object. I would define the following class and enum:
public class SignupDto {
private Status status;
private String message;
public SignupDto() {
}
public SignupDto(Status status, String message) {
this.status = status;
this.message = message;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public enum Status {
FAIL,
SUCCESS
}
}
And use it as following:
public SignupDto signup(HttpServletRequest request, HttpServletResponse response) {
return new SignupDto(SignupDto.Status.FAIL, "foo");
}
Jackson will do the serialising automatically.
Upvotes: 3