首页 > 解决方案 > 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 格式显示。

关于我可以用来解决这个问题的正确方法的任何建议?

标签: jsonspringcsv

解决方案


这是您的控制器:

@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


推荐阅读