使用Jackson库直接将CSV文件转换为JSON文件 [英] directly convert CSV file to JSON file using the Jackson library
本文介绍了使用Jackson库直接将CSV文件转换为JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下代码:
CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
ObjectMapper mapper = new CsvMapper();
File csvFile = new File("input.csv"); // or from String, URL etc
Object user = mapper.reader(?).withSchema(bootstrap).readValue(new File("data.csv"));
mapper.writeValue(new File("data.json"), user);
它在我的IDE中引发一个错误,说无法找到符号方法withSchema(CsvSchema )
但是为什么?我已经使用了一些例子的代码。
It throws an error in my IDE saying cannot find symbol method withSchema(CsvSchema)
but why? I have used the code from some examples.
我不知道要写入 mapper.reader()
我要转换任何CSV文件。
如何将任何CSV文件转换为JSON并保存到磁盘?
I don't know what to write into mapper.reader()
as I want to convert any CSV file.
How can I convert any CSV file to JSON and save it to the disk?
做下一个?示例
推荐答案
我认为,您应该使用 MappingIterator
问题。请参阅下面的示例:
I think, you should use MappingIterator
to solve your problem. See below example:
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
public class JacksonProgram {
public static void main(String[] args) throws Exception {
File input = new File("/x/data.csv");
File output = new File("/x/data.json");
List<Map<?, ?>> data = readObjectsFromCsv(input);
writeAsJson(data, output);
}
public static List<Map<?, ?>> readObjectsFromCsv(File file) throws IOException {
CsvSchema bootstrap = CsvSchema.emptySchema().withHeader();
CsvMapper csvMapper = new CsvMapper();
MappingIterator<Map<?, ?>> mappingIterator = csvMapper.reader(Map.class).with(bootstrap).readValues(file);
return mappingIterator.readAll();
}
public static void writeAsJson(List<Map<?, ?>> data, File file) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(file, data);
}
}
查看此页:jackson-dataformat-csv 了解更多信息和示例。
See this page: jackson-dataformat-csv for more information and examples.
这篇关于使用Jackson库直接将CSV文件转换为JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文