简体   繁体   中英

Java Spring: How to use @RequestBody to POST JSON Object

I am creating an API that receives the following input, and provides the following output. 在此处输入图片说明

I have already created a working method for "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);
}

Which returns the following JSON:

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

However, I need to create a function for making guesses. I have not had any luck. I have this as my function header, however it does not seem to be correct...

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

You probably want something like

@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;
}

However, if you're getting 404 Not Found , your problems are not with method definition, but that you're posting to wrong URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM