[英]Posting dynamic JSON-Object to Spring RESTful Web Service
我正在尝试发布动态JSON对象
{
"name":[
{
"key":"myKey1",
"value":"myValue1"
},
{
"key":"myKey2",
"value":myValue2
},
....
]
}
到Spring RESTful Web Service,但我想将JSON-Object作为JSON-Object而不是String来获取,我的代码是:
@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")
public Greeting hi(@RequestBody String jobject) {
return new Greeting (100,jobject);
}
由于需要键值对,因此可以执行以下操作:您可以定义一个包含地图的POJO。如下所示:
@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;
}
请求对象:
"params":{
"birthDate": "25.01.2011",
"lang":"en"
}
您可以将其获取为String并使用JSON.parse或类似的东西将其转换为json! 或者你可以使用
@RequestMapping(path ="/test", method = RequestMethod.POST, consumes = "application/json")
public myMethodehi(@RequestBody Pojo pojo) {
}
创建与您的json相对应的pojo类。
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+"]";
}
}
您可以使用一些在线json到pojo转换器。 我使用http://www.jsonschema2pojo.org/只需将json粘贴在其中,然后单击转换。
现在,Spring将代替您指定POJO类,而不是字符串。
@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")
public Greeting hi(@RequestBody MyPojo myPojo) {
// return new Greeting (100,jobject);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.