【问题标题】:Spring RESTful web service POST objectSpring RESTful Web 服务 POST 对象
【发布时间】:2017-10-19 08:21:11
【问题描述】:

我在使用 Spring 和 Gson 将我的对象发布到服务器时遇到问题。我得到的结果是空的,即使它包含数据。

这段代码 sn-p 来自 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}
 ]
}

我希望得到 2 的结果,但结果显示为 0。

【问题讨论】:

    标签: java json spring rest gson


    【解决方案1】:

    您需要发布 items 的元素,而不是发布 ServiceSettings 对象,因为控制器希望有效负载是一个列表。请尝试以下操作:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2011-09-30
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多