Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring mvc controller accept JSON object with variable number of keys/values

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.

like image 336
Barry Avatar asked Dec 26 '13 20:12

Barry


1 Answers

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{
like image 118
Sotirios Delimanolis Avatar answered Nov 15 '22 17:11

Sotirios Delimanolis