java 带有嵌套json到json对象的CSV

kxe2p93d  于 2023-01-11  发布在  Java
关注(0)|答案(2)|浏览(114)

我有一个示例CSV消息:

header1,header2,header3
value1,value2,{"name":"John","age":30,"car":null}

如何将其转换为嵌入式JSON的形式,如下所示:

{
  "header1": "value1",
  "header2": "value2",
  "header3": "{\"name\":\"John\",\"age\":30,\"car\":null}"
}

我正在使用Jackson架构生成器和默认列分隔符:

CsvSchema.builder().disableQuoteChar().setUseHeader(true).build();
CsvMapper.builder().enable(CsvParser.Feature.IGNORE_TRAILING_UNMAPPABLE, CsvParser.Feature.WRAP_AS_ARRAY).build();
s5a0g9ez

s5a0g9ez1#

您可以使用csv JS库,如json-2-csv

# Global so it can be called from anywhere
npm install -g json2csv

# or as a dependency of a project
npm install json2csv --save
emeijp43

emeijp432#

您可以按如下方式org.json.CDL

BufferedReader br = new BufferedReader(new FileReader("file.csv"));
        String csvAsString = br.lines().collect(Collectors.joining("\n"));
        String json = CDL.toJSONArray(csvAsString).toString();
        try {
            Files.write(Path.of("src/main/resources/output.json"), json.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }

相关问题