【问题标题】:Spring Annotation missing requestBodySpring Annotation 缺少 requestBody
【发布时间】:2020-03-30 18:59:39
【问题描述】:

我用一个简单的 post 和 get 方法编写了一个非常简单的控制器类。

今天是我第一次使用 Postman - 我不知道自己做错了什么,但每次使用 POST 映射时,我都会得到:

{
  "timestamp": "2020-03-29T19:05:49.548+0000",
  "status": 400,
  "error": "Bad Request",
  "message": "Required request body is missing: public int pl.futurecollars.controller.GreetingControler.saveGreeting(pl.futurecollars.controller.Greeting)",
  "path": "/greetings"
}

控制器类:

@RestController
@RequestMapping("/greetings")
public class GreetingControler {

    private Map<Integer, Greeting> greetings = new HashMap<>();
    private int counter = 0;

    @GetMapping
    public Collection<Greeting> getGreetings() {
        return greetings.values();
    }

    @PostMapping
    public int saveGreeting(@RequestBody Greeting greeting){
        greeting.setId(counter);
        greetings.put(counter, greeting);
        return counter++;
    }

    @DeleteMapping("/{id}")
    public void deleteGreeting(@PathParam("id") int greetingId){
        greetings.remove(greetingId);
    }
}

我添加了一个@RequestBody,但它仍然说它丢失了。

如何解决这个问题?

【问题讨论】:

  • 通过发送请求正文! (邮递员/curl/...?)
  • Greeting 类的外观如何?您如何提出您的要求?
  • curl = curl -X POST -H "Content-Type: application/json" -d '{... 问候 json ...}' localhost:8080/greetings {"timestamp":"2020- 03-29T19:19:03.648+0000","status":400,"error":"Bad Request","message":"JSON 解析错误:意外字符('.'(代码 46)):期待双倍- 引用开始字段名称;嵌套异常是 com.fasterxml.jackson.core.JsonParseException: Unexpected character ('.' (code 46)): was expected double-quote to start field name\n at [Source: (PushbackInputStream) ; line: 1, column: 3]","path":"/greetings"}j
  • ..当然我希望你能帮我/想一下{... greeting json ...}...我只是把它用作占位符:) ..我们不知道问候的样子喜欢。
  • @nazar_art - Greeting 类非常简单:两个字段,空的默认构造函数,getter 和 setter。

标签: java post controller postman


【解决方案1】:

错误消息对缺少的内容有明确的描述:

缺少必需的请求正文:...

因此,您错过了向请求添加正文。

您的配置应如下所示:

正文应该是 Greeting 类的 JSON 对象。
它应该发布到raw 选项卡。

另外,不要忘记header 上的适当 Content-Type

有用的链接:

【讨论】:

    【解决方案2】:

    首先根据您在评论中提到的错误验证您的输入,其中一个字段名以. 开头,而不是应该在"" 中。您可以在 https://jsoneditoronline.org/ 上验证您的 json。 还添加邮递员快照仅供参考 Inside postman -> Body where u can put payload

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 2014-10-26
      • 2023-03-31
      • 2016-02-14
      • 2018-03-18
      相关资源
      最近更新 更多