2017-03-17 49 views
0

我尝试后动态JSON-的物体,像发布动态JSON-对象春RESTful Web服务

{ 
    "name":[ 
     { 
     "key":"myKey1", 
     "value":"myValue1" 
     }, 
     { 
     "key":"myKey2", 
     "value":myValue2 
     }, 
     .... 
    ] 
} 

到Spring RESTful Web服务,但我想JSON-对象为JSON-对象不是字符串我的代码是:

@RequestMapping(path ="/hi", method = RequestMethod.POST, consumes = "application/json")  
public Greeting hi(@RequestBody String jobject) { 
return new Greeting (100,jobject); 
} 

回答

1

创建一个POJO类correspoding你的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+"]"; 
    } 
} 

你可以使用一些在线json pojo转换器。我使用 http://www.jsonschema2pojo.org/只需粘贴JSON那里,然后点击转换。

现在不是字符串指定POJO类,春天就会做转换为你

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

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

它的工作原理,但还是有些困惑,为什么当我想直接用出覆盖方法打印对象时,它给人的对象“[email protected]”的引用?当我将数组的键从“名称”更改为其他时,它会发生问题? –

+0

来打印,调用toString()方法。 'myPojo.toString();'。变量名应该和你的json中的键相同 – HeisenBerg

0

你可以得到它作为字符串,并将其转换为JSON与JSON.parse或类似的东西!或者您可以使用

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

} 
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"  
}