简体   繁体   中英

why is Spring Boot returning a string instead of JSON

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'}";
    }
}

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.

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\"}");
}

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