Reputation: 13915
My Spring @Controller
needs to access fields of a passed object in JSON format. I would like to avoid building many classes to map every request response to. For example, I need to connect store two foreign keys. They are passed as {"key1": 1,"key2": 2}
to the controller. How to access those fields if I don't have an object which has 2 fields to map those properties? How to set up the Spring controller method?
My code:
@RequestMapping(value = "/addProductPart", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String addProductPart(Model model, @RequestBody Object json,
BindingResult result){
// access somehow key1 and of json Object
UPDATE:
I know I can get it working using RequestMethod.GET
and @RequestParam
, but since I modify data I need RequestMethod.POST
or RequestMethod.PUT
.
SOLVED:
@RequestMapping(value = "/addProductPart", method = RequestMethod.PUT, consumes = "application/json")
@ResponseBody
public String addProductPart(Model model, @RequestBody Object obj){
...
int p = (Integer)((Map)obj).get("part");
...
}
Upvotes: 2
Views: 7751
Reputation: 8146
You can do something like :
@RequestMapping(value = "/addProductPart", method = RequestMethod.POST, consumes = "application/json")
@ResponseBody
public String addProductPart(@RequestBody GetData obj){
System.out.println(obj.jObj.getString("key1"));
}
Here GetData
is class that will receive data in it & map incoming data in it.
GetData class
:
public class GetData{
private JSONObject jObj;
//getter-setter
// if you are getting more than one element or array of json then :
private JSONArray jArray();
// getter-setter
}
if you want JSonArray then you can make operation on it.
It's related code tutorial is Here.
Still some problem then post me.
You can also use directly JSonObject
in method Invocation but if you are getting more data then it's better to use Class & pass it to there.
One thing to keep in mind that the Name of received JSonObject
& the Name declared in class
should be same.
Some problem POST me.
Upvotes: 1
Reputation: 279880
Spring, by default, uses Jackson to deserialize JSON. If you specify Object
as the parameter type, Jackson will deserialize the JSON to a LinkedHashMap
. You can cast the variable and access the elements through Map#get(Object)
.
Alternatively, you can declare your method parameter as some POJO type that fits the JSON structure and Jackson will deserialize to that type. You can then use its getters to retrieve your data.
Upvotes: 4