首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >OpenCSV + RestTemplate:数组类型

OpenCSV + RestTemplate:数组类型
EN

Stack Overflow用户
提问于 2020-03-31 06:25:16
回答 1查看 153关注 0票数 0

我尝试使用Spring的RestTemplate将远程CSV文件解析为bean。我想使用RestTemplate的原因是,它已经解决了Http连接的所有低级问题(主要是资源管理),并且我可以轻松地设置超时。

因此,我编写了一个自定义HttpMessageConverter,它使用OpenCSV将HttpMessage转换为CSV bean。该bean使用OpenCSV的相应CsvToBean注释进行注释。然而,问题是RestTemplate为您提供了您在中指定的类参数。

代码语言:javascript
复制
restTemplate.exchange("www.exmample.com", HttpMethod.GET, null, MyDTO.class)

上面的代码总是恰好返回一个MyDTO。如果您想要一个MyDTO列表,那么使用RestTemplate时,您必须指定以下内容:

代码语言:javascript
复制
restTemplate.exchange("www.exmample.com", HttpMethod.GET, null, MyDTO[].class)

然而,OpenCSV的工作方式有所不同。

代码语言:javascript
复制
final CsvToBeanBuilder<MyDTO> beanBuilder = new CsvToBeanBuilder<>(new InputStreamReader(httpInputMessage.getBody()));
beanBuilder.withType(MyDTO.class); // not sure of this is needed
beanBuilder.build().parse(); // returns List<MyDTO>

因此,OpenCSV接受DTO的单数非数组版本,它的parse-it-all函数返回给定内容的列表。问题是我在我的自定义HttpMessageConverter中使用了OpenCSV。因此,我被迫使用从RestTemplate获得的类类型:

代码语言:javascript
复制
// Inside of my class that extends HttpMessageConverter<T>

@Override
public T read(final Class<? extends T> aClass, final HttpInputMessage httpInputMessage) 
    throws IOException, HttpMessageNotReadableException {

  final CsvToBeanBuilder<T> beanBuilder = new CsvToBeanBuilder<>(new InputStreamReader(httpInputMessage.getBody()));
  beanBuilder.withType(aClass); // This throws an exception if aClass is of MyDTO[].class. 
                                // The exception states that there is no way to init the class.
  // This returns a List<Class<T>> which is already wrong. This findFirst() workaround could work but it fails earlier
  return beanBuilder.build().parse().stream().findFirst().orElse(null);
}

我能想到的唯一解决方案是将我真正想要的类硬编码到我的自定义HttpMessageConverter中。我希望避免这种情况,因为这样的话,这个消息转换器对项目的其余部分就没有可重用性。这个问题还有其他的解决方案吗?

EN

回答 1

Stack Overflow用户

发布于 2020-03-31 08:04:18

你会想要使用ParameterizedTypeReference。这样,您就可以将其解析为ParameterizedTypeReference>。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60940510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档