将动态JSON-Object发布到Spring RESTful Web服务

时间:2017-03-17 10:00:13

标签: java json spring rest

我正在尝试发布像

这样的动态JSON-Object
{  
   "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); 
}

3 个答案:

答案 0 :(得分:2)

由于您需要键值对,您可以执行以下操作: 您可以定义包含地图的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"       
 }

答案 1 :(得分:0)

你可以把它作为String并用JSON.parse或者像这样的东西将它转换为json !!或者你可以使用

@RequestMapping(path ="/test", method = RequestMethod.POST, consumes = "application/json")     
public myMethodehi(@RequestBody Pojo pojo) {  

}

答案 2 :(得分:0)

为你的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粘贴到那里,然后点击转换。

现在代替字符串指定您的POJO类,spring将为您进行转换

@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")     
public Greeting hi(@RequestBody MyPojo myPojo) {  

    // return new Greeting (100,jobject); 
}