directly convert CSV file to JSON file using the Jackson library

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

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.

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?

What to do next? The examples

回答1:

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);     } }

See this page: jackson-dataformat-csv for more information and examples.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!