Java 使用 Jackson 库直接将 CSV 文件转换为 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19766266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
directly convert CSV file to JSON file using the Hymanson library
提问by Daniel Ruf
I am using following code:
我正在使用以下代码:
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);
It throws an error in my IDE saying cannot find symbol method withSchema(CsvSchema)
but why? I have used the code from some examples.
它在我的 IDE 中抛出一个错误,cannot find symbol method withSchema(CsvSchema)
但为什么?我使用了一些示例中的代码。
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?
我不知道该写什么,mapper.reader()
因为我想转换任何 CSV 文件。
如何将任何 CSV 文件转换为 JSON 并将其保存到磁盘?
What to do next? The examples
接下来做什么?例子
采纳答案by Micha? Ziober
I think, you should use MappingIterator
to solve your problem. See below example:
我想,你应该用它MappingIterator
来解决你的问题。见下面的例子:
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.fasterxml.Hymanson.databind.MappingIterator;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.dataformat.csv.CsvMapper;
import com.fasterxml.Hymanson.dataformat.csv.CsvSchema;
public class HymansonProgram {
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);
}
}
See this page: Hymanson-dataformat-csvfor more information and examples.
有关更多信息和示例,请参阅此页面:Hymanson-dataformat-csv。