13

I know the JSON object I need to accept will always be single keys and values. I attempted to write my Spring MVC controller with @RequestBody Map and @RequestBody Map however I always get 400 Bad Request. When I change my @RequestBody to a String I see my data come through and no Bad Request response is returned.Is it possible to write something to accept an arbitrary JSON object that will always conform to the contract of being a single key to a single value?

@RequestMapping(value = "/advancedSearch", method = RequestMethod.POST,consumes ="application/json",produces = "application/json")
@ResponseBody
public MyResponse performAdvancedSearch(@RequestBody String advancedFormData) throws Exception{

this is the mapping that is working right now with String...

sample JSON-

    {"name":"frank","Type":"Lumber"}

when posting from front-end I call JSON.stringify() to create data.Again, the JSON will always be simple like this no nested lists/objects just straight key/values. The server side just never knows how many key value pairs will come in and it has no knowledge of all the potential keys so I can't create a simple POJO.

2
  • Please post your handler method that fails and the body of the request that you send. Commented Dec 26, 2013 at 20:08
  • are you using application/json content-type ? Commented Dec 26, 2013 at 20:08

1 Answer 1

10

Make your life simple and create a class

public class AdvancedFormData
    private String name;
    private String type; // make it lower case in your JSON too
    // appropriate getters and setters and a no-arg constructor for Jackson
}

and use

public MyResponse performAdvancedSearch(@RequestBody AdvancedFormData advancedFormData) throws Exception{
Sign up to request clarification or add additional context in comments.

5 Comments

The point of my question was that I won't know all the potential keys like (name & type) so I can't use a class like this.
@Barry Ok, please show the solution you were trying with Map.
it was the same exact handler as above but instead of RequestBody String advancedFormData it was RequestBody Map<String,String> advancedFormData or RequestBody Map<String,Object> advancedFormData both kept giving me 400/Bad Request.
@Barry With Spring MVC 4, @RequestBody Map<String, Object> map works for me with the input json {"name":"frank","Type":"Lumber"}. If you are on a different Spring version, please specify it and provide your servlet context configuration.
Using Spring MVC 3.2.3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.