简体   繁体   English

Java,CSV转换为json,jackson-dataformat-csv

[英]Java , Csv to json , jackson-dataformat-csv

I am novice in java and I want to convert csv file into json 我是Java的新手,我想将csv文件转换为json

I'am using the following code example to convert csv file into json file, the things is, I have got an error on the" withSchema(bootstrap) " it says : "The method with(CsvSchema) is undefined for the type ObjectReader" and I do not know how to fix it, I have change maven dependencies to the version 2.9.0, try withtype(bootstrap) withCsvSchema(bootstap) but still not working . 我正在使用下面的代码示例将csv文件转换为json文件,事实是,我在“ withSchema(bootstrap)”上显示错误:它说:“类型(ObjectReader)的with(CsvSchema)方法未定义”而且我不知道如何解决它,我已经将Maven依赖项更改为版本2.9.0,请尝试withtype(bootstrap)withCsvSchema(bootstap)但仍然无法正常工作。

Thanks 谢谢

Here is the code : 这是代码:

package CsvData;

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 csvjson {

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

正确的方法名称为withSchema

csvMapper.reader(Map.class).withSchema(bootstrap).readValues(file);

I tried with version 2.2.1 and it works fine for me. 我尝试使用2.2.1版,它对我来说很好用。

<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-csv</artifactId>
<version>2.2.1</version>

Here is the Java method 这是Java方法

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

Even document says it works since 2.2 but dnt know why it is not working for 2.9.0. 甚至文档说它从2.2开始就可以使用,但是dnt知道为什么它不适用于2.9.0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM