简体   繁体   中英

Spring RequestBody convert JSON to String

I have a RestController class which has a method to search for a Film by its title:

@RequestMapping(value = "/film", method = RequestMethod.POST,
               consumes = "application/json", produces = "application/json")
public Film getFilm(@RequestBody String filmSearch){
    FilmInfo filmInfo = new FilmInfo();
    Film film = filmInfo.getFilm(filmSearch);
    return film;
}

If I send a json String

{
 "filmSearch":"<title>"
} 

to the endpoint from Postman I receive a blank response back.

I then did a

System.out.println(filmSearch)

right after entering the method to find the String filmSearch was exactly the JSON string I sent from Postman. My application is not seeing the JSON and extracting the value from filmSearch in my request to attach to the in-app String filmSearch.

If I remove the

consumes = "application/json" 

part in the RequestMapping and send over a plain text string of the title it works and I get a Film object sent back as JSON.

I'd rather not use plain text in my search term though, how can I correctly have my JSON be converted into a String on entering the method?

If you add request body is not Object. 而不是Object。 Server received is String json not OBJECT. You can try code:

@RequestMapping(value = "/film", method = RequestMethod.GET, produces = "application/json")
public Film getFilm(@RequestParam("search") String search){
    FilmInfo filmInfo = new FilmInfo();
    Film film = filmInfo.getFilm(search);
    return film;
}

If you user postman:

  • URL: /flim?search=minion
  • Method: GET
  • Header: Content-Type: application/json

It's because you're passing the entire JSON payload as a string inside the 'getfilm()' function. What you're expecting to call is getfilm(<title>) , but you're actually calling is getfilm({"filmSearch":"<title>"} ) , which is wrong. The best choice would be, convert that string to JSON, say like this

JSONObject jsonstring = new JSONObject(filmSearch);
FilmInfo filmInfo = new FilmInfo();
Film film = filmInfo.getFilm(jsonstring.get("title"));

you can also ignore the 'consumes = "application/json"' from the request mapping.

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