我尝试使用Spring的RestTemplate将远程CSV文件解析为bean。我想使用RestTemplate的原因是,它已经解决了Http连接的所有低级问题(主要是资源管理),并且我可以轻松地设置超时。
因此,我编写了一个自定义HttpMessageConverter,它使用OpenCSV将HttpMessage转换为CSV bean。该bean使用OpenCSV的相应CsvToBean注释进行注释。然而,问题是RestTemplate为您提供了您在中指定的类参数。
restTemplate.exchange("www.exmample.com", HttpMethod.GET, null, MyDTO.class)上面的代码总是恰好返回一个MyDTO。如果您想要一个MyDTO列表,那么使用RestTemplate时,您必须指定以下内容:
restTemplate.exchange("www.exmample.com", HttpMethod.GET, null, MyDTO[].class)然而,OpenCSV的工作方式有所不同。
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获得的类类型:
// 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中。我希望避免这种情况,因为这样的话,这个消息转换器对项目的其余部分就没有可重用性。这个问题还有其他的解决方案吗?
发布于 2020-03-31 08:04:18
你会想要使用ParameterizedTypeReference。这样,您就可以将其解析为ParameterizedTypeReference>。
https://stackoverflow.com/questions/60940510
复制相似问题