让JSON Post在Spring Boot中工作

时间:2016-06-21 02:57:33

标签: java json spring rest spring-boot

我正在尝试使用JSON对我正在运行的Spring Boot应用程序进行POST调用,每次进行POST调用时都会出现以下错误

Request method 'POST' not supported

这是我的控制器的基本布局,

@RestController
public class MessagesController {

    @RequestMapping(value = "/messages", method = RequestMethod.POST)
    public @ResponseBody Answer processMessage(@RequestBody Message message) throws Exception{
        System.out.println("HERE");

        Answer a = new Answer(5);

        return a;
    }

    @ExceptionHandler
    void handleException(Exception e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.CONFLICT.value());
    }
}

MessageAnswer是POJO

public class Message implements Serializable{
    private int id;
    private int description;

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description= description;
    }
}

public class Answer implements Serializable{
    private int answer;

    public Answer(int answer){
        this.answer = answer;
    }

    public int getAnswer() {
        return answer;
    }

    public void setAnswer(int answer) {
        this.answer = answer;
    }
}

我希望能够将JSON POST到我的控制器,然后再接收JSON消息。如何在没有错误的情况下使其工作?我通过SoapUI发布到http://localhost:8080/messages

1 个答案:

答案 0 :(得分:1)

所以这就是我的想法:
描述的类型不应该是String而不是int?

private int description;
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description= description;
}

你的帖子json应该是:(假设id是整数,而descripion是String)

{"id": 1, "descripion":"Test message"}

尝试像这样转动你的Rest控制器:

@RestController
@RequestMapping("messages")
public class MessagesController {
    @RequestMapping(method = RequestMethod.POST)
    public Answer processMessage(@RequestBody Message message) throws Exception{