我遇到了Spring和Gson将我的对象发送到服务器的麻烦。我得到的结果是空的,即使它包含数据。
此代码段来自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。
答案 0 :(得分:0)
而不是POST var compilation = await project.GetCompilationAsync();
//Add Module
compilation.AddReferences(ModuleMetadata.CreateFromFile(@"c:\artifacts\MyLib.netmodule").GetReference());
compilationStatus = compilation.Emit(outputFolderPath + @"\Test1.dll", outputFolderPath + @"\Test1.pdb");
if (!compilationStatus.Success)
{
foreach (var item in compilationStatus.Diagnostics)
{
Console.WriteLine(item);
}
}
对象,您需要发布它的ServiceSettings
元素,因为控制器期望有效负载是一个列表。请尝试以下方法:
items