I am trying to post dynamic JSON-Object like
{
"name":[
{
"key":"myKey1",
"value":"myValue1"
},
{
"key":"myKey2",
"value":myValue2
},
....
]
}
to Spring RESTful Web Service but I want to get JSON-Object as JSON-Object not as String my code is:
@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")
public Greeting hi(@RequestBody String jobject) {
return new Greeting (100,jobject);
}
Since you need key-value pairs , you can do something like below: You can define a POJO which contains a map.. Something like below:
@RequestMapping(value = "/get/{searchId}", method = RequestMethod.POST)
public String search(
@PathVariable("searchId") Long searchId,
@RequestParam SearchRequest searchRequest) {
System.out.println(searchRequest.getParams.size());
return "";
}
public class SearchRequest {
private Map<String, String> params;
}
Request Object:
"params":{
"birthDate": "25.01.2011",
"lang":"en"
}
you can get it as String and convert it to json with JSON.parse or somthing like that !! or you can use
@RequestMapping(path ="/test", method = RequestMethod.POST, consumes = "application/json")
public myMethodehi(@RequestBody Pojo pojo) {
}
Create a pojo class correspoding to your json.
public class MyPojo
{
private Name[] name;
public Name[] getName ()
{
return name;
}
public void setName (Name[] name)
{
this.name = name;
}
@Override
public String toString()
{
return "ClassPojo [name = "+name+"]";
}
}
public class Name
{
private String value;
private String key;
public String getValue ()
{
return value;
}
public void setValue (String value)
{
this.value = value;
}
public String getKey ()
{
return key;
}
public void setKey (String key)
{
this.key = key;
}
@Override
public String toString()
{
return "ClassPojo [value = "+value+", key = "+key+"]";
}
}
You can use some online json to pojo converter. I use http://www.jsonschema2pojo.org/ Just paste json there and click convert.
Now instead of string specify your POJO class, spring will do the conversion for you
@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")
public Greeting hi(@RequestBody MyPojo myPojo) {
// return new Greeting (100,jobject);
}