Java Spring:如何使用@RequestBody来POST JSON对象

时间:2018-04-27 19:53:49

标签: java json spring rest

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

我已经为“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) 

1 个答案:

答案 0 :(得分: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,则问题不在于方法定义,而在于您发布的错误网址。