2017-10-19 94 views
-1

我遇到了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.

回答

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