使用 Jackson 库直接将 CSV 文件转换为 JSON 文件 [英] directly convert CSV file to JSON file using the Jackson library

查看:37
本文介绍了使用 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 中抛出一个错误,说 cannot find symbol method 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆