Spring REST风格的Web服务POST对象
问题描述:
我遇到了Spring和Gson将我的对象发布到服务器的麻烦。我得到的结果是空的,即使它包含数据。Spring REST风格的Web服务POST对象
此代码段是从RESTful Web服务:
@RequestMapping("/summe")
public @ResponseBody String summe(ArrayList<ServiceSettingsListItem> list) {
return "Greeting.summe() = <" + list + ">" + list.size();
}
我的客户:
private static Gson gson = new GsonBuilder().create();
public static void main(String[] args) throws IOException {
String fileContent = new String(Files.readAllBytes(new
File("demo.json").toPath()));
ServiceSettings serviceSettings = gson.fromJson(fileContent,
ServiceSettings.class);
String baseUrl = serviceSettings.getUrl();
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(baseUrl, serviceSettings, String.class);
System.out.println(result);
}
public static class ServiceSettings {
@Override
public String toString() {
return "ServiceSettings [url=" + url + ", test=" + test + ", items="
+ items + "]";
}
private String url;
private int test;
private ArrayList<ServiceSettingsListItem> items = new ArrayList<>();
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getTest() {
return test;
}
public void setTest(int test) {
this.test = test;
}
public ArrayList<ServiceSettingsListItem> getItems() {
return items;
}
public void setItems(ArrayList<ServiceSettingsListItem> items) {
this.items = items;
}
}
public static class ServiceSettingsListItem {
private String name;
private int value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
}
这里是我的JSON:
{"url":"http://localhost:8080/summe",
"test":123,
"items":[
{"name":"name1","value":5},
{"name":"name1","value":6}
]
}
我希望得到一个答案但是结果表明它是0.
答
而不是发布ServiceSettings
对象,您需要发布items
元素,因为控制器期望有效负载为列表。请尝试以下操作:
ServiceSettings serviceSettings = gson.fromJson(fileContent, ServiceSettings.class);
String baseUrl = serviceSettings.getUrl();
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.postForObject(baseUrl, serviceSettings.getItems(), String.class); //Assuming there is a getter for items