5

我正在使用 SpringRestTemplate对 REST Web 服务进行调用。其中一个调用是返回特定类型的对象列表。这些RestTemplate方法要求提供类参数以指示预期的返回类型。

// restTemplate is type org.springframework.web.client.RestTemplate
URI restServiceURI = new URI("http://example.com/foo")
restTemplate.getForObject(restServiceURI, List<Foo>.class);

显然,这不会编译。当您提供这样的类型参数时,您无法获得静态.class属性。当我删除类型参数时,代码会编译,但这会产生rawtypes编译器警告。

我的问题很简单。我是坚持抑制编译器警告还是有更简洁的方法来编写代码?

4

1 回答 1

3

但是 RestTemplate 怎么知道将列表元素转换为 class 的实例Foo?您是否尝试过运行代码,它是否按预期工作?

我能想到的一种方法是使用 Array 作为输入类型。例如。

restTemplate.getForObject(restServiceURI, Foo[].class);

但不知道是否支持。如果你真的需要反序列化更复杂的数据类型,那么你应该考虑使用 Jackson 或 Gson。

使用 Jackson,您可以使用ObjectMapper类轻松反序列化来自大多数来源的数据。

String input = ...;
ObjectMapper mapper = new ObjectMapper();
List<Foo> list = mapper.readValue(input, new TypeReference<List<Foo>>(){});

上述工作是因为您有意创建了一个扩展 TypeReference 的匿名类,该类将在运行时记住其泛型类型,因此它可以帮助对象映射器创建 Foo 列表。为了更全面的解释

于 2011-12-14T18:28:12.707 回答