在Java Springboot中将CSV转换为JSON数组

xxe27gdn  于 2022-12-18  发布在  Spring
关注(0)|答案(3)|浏览(174)

嗨,我正试图使用一个名为csvReader的依赖项将CSV文件转换为JSON数组,但当我运行代码时,它错误地打印出JSON响应,我想知道为什么有人能给我指出正确的方向。

@GetMapping("/convert")
    public List<List<String>> convertCSV() throws FileNotFoundException {
        List<List<String>> records = new ArrayList<List<String>>();
    try (CSVReader csvReader = new CSVReader(new FileReader("C:/Download/cities.csv"));) {
        String[] values = null;

    while ((values = csvReader.readNext()) != null) {
        records.add(Arrays.asList(values));
    }

} catch (IOException e) {
            e.printStackTrace();
        }
        return values;
    }

8fsztsew

8fsztsew1#

你的案子没什么大不了的。
您可以读取csv并构建json
读取第一行并确定列。其余行为值。

public class Foo{

    public static void main(String[] args) throws Exception{

        List<String> csvRows = null;
        try(var reader = Files.lines(Paths.get("dataFile.csv"))){
            csvRows = reader.collect(Collectors.toList());
        }catch(Exception e){
            e.printStackTrace();
        }

        if(csvRows != null){

            String json = csvToJson(csvRows);
            System.out.println(json);

        }

    }

    public static String csvToJson(List<String> csv){

        //remove empty lines
        //this will affect permanently the list. 
        //be careful if you want to use this list after executing this method
        csv.removeIf(e -> e.trim().isEmpty());

        //csv is empty or have declared only columns
        if(csv.size() <= 1){
            return "[]";
        }

        //get first line = columns names
        String[] columns = csv.get(0).split(",");

        //get all rows
        StringBuilder json = new StringBuilder("[\n");
        csv.subList(1, csv.size()) //substring without first row(columns)
            .stream()
            .map(e -> e.split(","))
            .filter(e -> e.length == columns.length) //values size should match with columns size
            .forEach(row -> {

                json.append("\t{\n");

                    for(int i = 0; i < columns.length; i++){
                        json.append("\t\t\"")
                            .append(columns[i])
                            .append("\" : \"")
                            .append(row[i])
                            .append("\",\n"); //comma-1
                    }

                    //replace comma-1 with \n
                    json.replace(json.lastIndexOf(","), json.length(), "\n");

                json.append("\t},"); //comma-2

            });

        //remove comma-2
        json.replace(json.lastIndexOf(","), json.length(), "");

        json.append("\n]");

        return json.toString();

    }

}

测试日期:

fname,lname,note
Shaun,Curtis,a
Kirby,Beil,b

-----------------------

[
    {
        "fname" : "Shaun",
        "lname" : "Curtis",
        "note" : "a"
    },  {
        "fname" : "Kirby",
        "lname" : "Beil",
        "note" : "b"
    }
]

该方法适用于csv的任意结构,不需要Map列。

bhmjp9jg

bhmjp9jg2#

这是因为你阅读字符串中的数据并打印字符串列表。如果你想将CSVMap到对象(JSON对象),你需要将CSV读取为bean对象,请找到以下代码片段以打印为JSON,将toString方法重写为JSON格式。
User.java

public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    private String name;

    @NotNull
    private String surname;

    //Getter and Setters
}

CsvReaderUtil.java

public static List<User> readCsvFile() throws IOException {
            List<User> list = null;
            CSVReader reader = null;
            InputStream is = null;
            try {
                File initialFile = new File("C:\\Users\\ER\\Desktop\\test.csv");
                is = new FileInputStream(initialFile);
                reader = new CSVReader(new InputStreamReader(is), ',', '"', 1);
                ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
                strat.setType(User.class);
                String[] columns = new String[]{"id", "name", "surname"};
                strat.setColumnMapping(columns);
                CsvToBean csv = new CsvToBean();
                list = csv.parse(strat, reader);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                is.close();
                reader.close();
            }
            return list;
        }

现在将这个用户列表打印为JSON对象。

mi7gmzs6

mi7gmzs63#

下面是一个如何使用Java 11+将CSV转换为JSON的有用示例:

private String fromCsvToJson(String csvFile) {
    String[] lines = file.split("\n");

    if (lines.length <= 1) {
        return List.of();
    }

    var headers = lines[0].split(",");
    var jsonFormat = Arrays.stream(lines)
                           .skip(1)
                           .map(line -> line.split(","))
                           .filter(line -> headers.length == line.length)
                           .map(line -> IntStream.range(0, headers.length).boxed().collect(toMap(i -> headers[i], i -> line[i], (a, b) -> b)))
                           .toList();

    return new ObjectMapper().writeValueAsString(jsonFormat);
}

相关问题