java - 让 JSON Post 在 Spring Boot 中工作

标签 java json spring rest spring-boot

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

Request method 'POST' not supported

这是我的 Controller 的基本布局,

@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 发布到我的 Controller ,然后接收返回的 JSON 消息。我怎样才能让它工作而不出现错误?我通过 SoapUI 发布到 http://localhost:8080/messages

最佳答案

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

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

您的帖子 json 应该是:(假设 id 是整数,描述是字符串)

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

尝试像这样转动你的 Rest Controller :

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

关于java - 让 JSON Post 在 Spring Boot 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37934850/

相关文章:

java - Gson 使用 InstanceCreator 反序列化嵌套对象

c# - 杰森,网不工作

javascript - JSON - 在 Internet Explorer 8 中不起作用

java - 无论如何将构造函数参数传递给 JAXB 适配器?

java - MySQL : Communication Link failure error and telnet localhost 3306 : Connection close

java - BlueJ - 找不到tools.jar

javascript - JSON 和 JS 回调函数

java - Spring/RestTemplate - PUT 实体到服务器

spring - spring中jdbctemplate和事务管理的java配置

java - 如何使用 jdbc/spring-jdbc 不使用 PGInterval 对 PostgreSQL 区间数据类型进行操作?