簡體   English   中英

使用 Jackson 庫直接將 CSV 文件轉換為 JSON 文件

[英]directly convert CSV file to JSON file using the Jackson library

我正在使用以下代碼:

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 中拋出一個錯誤,說cannot find symbol method withSchema(CsvSchema)但為什么? 我已經使用了一些示例中的代碼。

我不知道在mapper.reader()中寫入什么,因為我想轉換任何 CSV 文件。
如何將任何 CSV 文件轉換為 JSON 並將其保存到磁盤?

接下來做什么? 例子

我認為,您應該使用MappingIterator來解決您的問題。 請參見下面的示例:

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();
        try (MappingIterator<Map<?, ?>> mappingIterator = csvMapper.readerFor(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM