我正在寻找可以转换包含嵌套对象(例如:address.city,address.country)的csv数据的java库,以相应地转换为带有嵌套对象的json数据。 以下是我正在使用的Java代码:
File input = new File("input.csv");
File output = new File("output.json");
CsvSchema csvSchema = CsvSchema.builder()
.setUseHeader(true).build();
CsvMapper csvMapper = new CsvMapper();
// Read data from CSV file
List<Object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();
System.out.println(readAll);
ObjectMapper mapper = new ObjectMapper();
// Write JSON formated data to output.json file
mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);
// Write JSON formated data to stdout
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));
这是我得到的输出:
[ {
"studentName" : "Foo",
"Age" : "12",
"address__city" : "newyork",
"address__address1" : "North avenue",
"address__zipcode" : "123213",
"subjects__name" : "English",
"subjects__marks" : "40"
}, {
"studentName" : "ABcd",
"Age" : "25",
"address__city" : "achi",
"address__address1" : "Morh",
"address__zipcode" : "27400",
"subjects__name" : "History",
"subjects__marks" : "50"
} ]
这是预期的输出:
{
"studentName": "Foo",
"Age": "12",
"address":{
"city" : "newyork",
"address1": "North avenue",
"zipcode" : "123213"
},
"subjects": [
{
"name": "English",
"marks": "40"
},
{
"name": "History",
"marks": "50"
}
]
}
这是输入的csv:
"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","25","achi","Morh","2400","History","
答案 0 :(得分:0)
univocity-parsers似乎可以通过其@Nested
注释在CSV端完成您需要的工作。
虽然不能读取/写入JSON。因此,我的建议是使用单一性解析器将CSV解析为所需的对象结构,然后使用Jackson将该对象结构写入JSON。
希望这会有所帮助。 披露:我是唯一性分析器的作者。它是开源且免费的(Apache 2.0许可证)