【问题标题】:Java Spring: How to use @RequestBody to POST JSON ObjectJava Spring:如何使用@RequestBody POST JSON 对象
【发布时间】:2018-04-27 19:53:49
【问题描述】:

我正在创建一个接收以下输入并提供以下输出的 API。

我已经为“new”创建了一个工作方法:

@RequestMapping(value = "/new", method = RequestMethod.GET)
public StartedGame startGame(HttpSession session){
    List<Game> games = getCurrentGames(session);
    Game newGame = new Game(wordList);
    games.add(newGame);
    return new StartedGame(newGame);
}

返回以下 JSON:

{
    "gameId": "kvmuyw",
    "word": "_______"
}

但是,我需要创建一个用于猜测的函数。我没有运气。我有这个作为我的函数头,但它似乎不正确......

@RequestMapping(value = "/guess", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public Game makeGuess(@RequestBody String json, HttpSession session) 

【问题讨论】:

  • 好像不对……:为什么?你在做什么?你期望会发生什么?相反会发生什么?要精确。请注意,JSON 的全部意义在于它可以映射到对象。为什么将 String json 作为参数并自己解析它,而不是将 Guess 对象作为参数并让 Spring(实际上是杰克逊)将 JSON 映射到 Guess 对象?
  • 我收到 404 错误。我期望发生的事情在图片上方。
  • 你点击了什么网址?你发了什么json?你是怎么寄的?当您的应用程序启动时,您是否在日志中看到它映射了 /guess 端点?
  • @JBNizet 这是一些输出,带有解释:stackoverflow.com/questions/50071720/…
  • @ohbrobig 您说您收到 404 错误,然后在该问题中您在标题中说您收到 415 错误,而您粘贴的输出显示 500 错误...

标签: java json spring rest


【解决方案1】:

你可能想要类似的东西

@RequestMapping(value = "/guess", method = RequestMethod.POST,
   consumes = "application/json", produces = "application/json")
public Game makeGuess(@RequestBody Guess guess){
  // ..
}

@Data // <- this assuming you're using Lombok - add required accessors if not
public class Guess {
  String game;
  String guess;
}

但是,如果您收到 404 Not Found,则问题不在于方法定义,而在于您发布到错误的 URL。

【讨论】:

  • 我尝试使用 Guess 对象(带有 getter 和 setter)...我可能发布到错误的 URL。使用上述方法,什么是合适的 URL?
  • 假设JSON对象与上图类似。
  • @ohbrobig 正确的 url 是 /guess,假设您在控制器级别或应用程序没有额外的映射。如果有,则为/controllerurlvalue/guess/applicationurlvalue/controllerurlvalue/guess。 spring app启动时可以从日志中看到注册的url。
  • @ohbrobig 如果你得到错误500 和你声称here 一样的nullpointerexception,这至少意味着你的url 映射工作正常,所以显然你得到了这个工作
猜你喜欢
  • 2014-08-05
  • 2019-11-10
  • 2017-08-23
  • 2020-05-29
  • 2015-06-21
  • 1970-01-01
  • 2011-10-25
  • 2018-01-23
  • 2019-05-28
相关资源
最近更新 更多