json - Spring Boot - 在 URI 处读取 CSV 文件并将其作为 JSON 返回
问题描述
我正在尝试编写一个将执行以下操作的 Spring Boot 应用程序:
在向主控制器 /all 发出 GET 请求时,它需要生成对特定 URI 的请求(http://prod.publicdata.landregistry.gov.uk.s3-website-eu-west-1.amazonaws.com/pp-每月更新新版本.csv),这将触发 CSV 文件下载。之后,它需要自动读取该文件,将其转换为 JSON 并以 JSON 格式显示。
关于我可以用来解决这个问题的正确方法的任何建议?
解决方案
这是您的控制器:
@RestController
@RequestMapping("/all")
public class MainController {
private static final String URL = "http://prod.publicdata.landregistry.gov.uk.s3-website-eu-west-1.amazonaws.com/pp-monthly-update-new-version.csv";
@GetMapping
public List<PricePaid> getDoc() {
RestTemplate restTemplate = new RestTemplate();
List<PricePaid> pricePaidList = restTemplate.execute(URL, HttpMethod.GET, null, clientHttpResponse -> {
InputStreamReader reader = new InputStreamReader(clientHttpResponse.getBody());
CsvToBean<PricePaid> csvToBean = new CsvToBeanBuilder<PricePaid>(reader)
.withType(PricePaid.class)
.withSeparator(',')
.withIgnoreLeadingWhiteSpace(true)
.build();
return csvToBean.stream().collect(Collectors.toList());
});
return pricePaidList;
}
}
请注意,我正在使用opencsv
库来解析下载的 .csv 并将其转换为PricePaid
对象列表。
这也是PricePaid
课程:
public class PricePaid {
@CsvBindByPosition(position = 0)
private String id;
@CsvBindByPosition(position = 1)
private Integer price;
@CsvBindByPosition(position = 2)
private String dateOfTransfer;
@CsvBindByPosition(position = 3)
private String postCode;
@CsvBindByPosition(position = 4)
private String propertyType;
@CsvBindByPosition(position = 5)
private String oldNew;
@CsvBindByPosition(position = 6)
private String duration;
@CsvBindByPosition(position = 7)
private String paon;
@CsvBindByPosition(position = 8)
private String saon;
@CsvBindByPosition(position = 9)
private String street;
@CsvBindByPosition(position = 10)
private String locality;
@CsvBindByPosition(position = 11)
private String city;
@CsvBindByPosition(position = 12)
private String district;
@CsvBindByPosition(position = 13)
private String county;
@CsvBindByPosition(position = 14)
private String ppd;
@CsvBindByPosition(position = 15)
private String recordStatus;
public PricePaid() {
}
// getters and setters
}
项目可以在 GitHub 上找到:https ://github.com/Ernyoke/price-paid-data
推荐阅读
- java - 我想通过单击外部 recyclerview 上的按钮来添加内部网格视图
- flask - flask 和 tailwind - 渲染时不使用 master.css 中的更改
- sql - ORA-00907:缺少右括号 00907. 00000 - “缺少右括号” *原因:*操作:
- r - 最大和最小周期之间的时间
- autodesk-forge - 尝试使用演示但无法找出问题所在
- jenkins - 集成测试无法连接到 Jenkins 中的 Postgres 9.6 Db
- alexa - 推送要与 Alexa 对话的消息
- css - 带有 vue 的 Plotly.js 在调整大小和数据更改时消失图表
- c# - 即使统一构建,omnisharp 也找不到命名空间
- java - 将数据添加到 firebase 实时数据库显示错误