Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing json into java objects in spring-mvc

I'm familiar with how to return json from my @Controller methods using the @ResponseBody annotation.

Now I'm trying to read some json arguments into my controller, but haven't had luck so far. Here's my controller's signature:

@RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") @RequestBody SearchRequest json) { 

But when I try to invoke this method, spring complains that: Failed to convert value of type 'java.lang.String' to required type 'com.foo.SearchRequest'

Removing the @RequestBody annotation doesn't seem to make a difference.

Manually parsing the json works, so Jackson must be in the classpath:

// This works @RequestMapping(value = "/ajax/search/sync") public ModelAndView sync(@RequestParam("json") String json) {     SearchRequest request;     try {         request = objectMapper.readValue(json, SearchRequest.class);     } catch (IOException e) {         throw new IllegalArgumentException("Couldn't parse json into a search request", e);     } 

Any ideas? Am I trying to do something that's not supported?

like image 371
oksayt Avatar asked Oct 13 '10 07:10

oksayt


People also ask

How do you pass a JSON object as a parameter in Java?

Either use an export mapping to create a JSON string that you can pass to the Java action and then create a JSON object again from that string or just pass a root object to the Java and then in Java retrieve all the attached objects over the references to that root object.

Can we parse JSON in Java?

JSON Processing in Java : The Java API for JSON Processing JSON. simple is a simple Java library that allow parse, generate, transform, and query JSON.

How do I convert JSON to Java manually?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

Your parameter should either be a @RequestParam, or a @RequestBody, not both.

@RequestBody is for use with POST and PUT requests, where the body of the request is what you want to parse. @RequestParam is for named parameters, either on the URL or as a multipart form submission.

So you need to decide which one you need. Do you really want to have your JSON as a request parameter? This isn't normally how AJAX works, it's normally sent as the request body.

Try removing the @RequestParam and see if that works. If not, and you really are posting the JSON as a request parameter, then Spring won't help you process that without additional plumbing (see Customizing WebDataBinder initialization).

like image 86
skaffman Avatar answered Oct 01 '22 10:10

skaffman