Java API,用于从 CSV 文件创建对象 [已关闭]

2022-09-01 11:46:28

我正在寻找一个允许我将.csv内容映射到对象的库。

像这样:

public class Person {

    private String name;
    private int age;

    @CsvField("name")
    public String getName() {
        return this.name;
    }

    @CsvField("age")
    public int getAge() {
        return this.age;
    }
}

然后说这样的话:

final Person filledWithDataFromCsv = csvApi.load(csvFilepath, Person.class);

从给定的 CSV:

#name, age
tom, 11
jim, 32

有没有人知道这样的API,或者一个做类似事情的API。我不希望它必须使用注释,我只是希望能够使用一行代码和预定义的类加载文件。


答案 1

JSefa 允许您注释可在序列化和反序列化过程中使用的 Java 类。本教程演示了如何使用 CsvIOFactory 类。

(摘自教程)为 Bean 添加注释就像在值列表中指定项目的位置一样简单,如有必要,您需要指定转换格式:

@CsvDataType()
public class Person {
    @CsvField(pos = 1)
    String name;

    @CsvField(pos = 2, format = "dd.MM.yyyy")
    Date   birthDate;
}

答案 2

使用uniVocity解析器不会出错。它支持各种强大的操作,并且比任何其他Java CSV解析器都要快得多。

下面是一个包含一些示例的类:

class TestBean {

    // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @NullString(nulls = { "?", "-" })
    // if a value resolves to null, it will be converted to the String "0".
    @Parsed(defaultNullRead = "0")
    private Integer quantity;   // The attribute type defines which conversion will be executed when processing the value.

    @Trim
    @LowerCase
    // the value for the comments attribute is in the column at index 4 (0 is the first column, so this means fifth column in the file)
    @Parsed(index = 4)
    private String comments;

    // you can also explicitly give the name of a column in the file.
    @Parsed(field = "amount")
    private BigDecimal amount;

    @Trim
    @LowerCase
    // values "no", "n" and "null" will be converted to false; values "yes" and "y" will be converted to true
    @BooleanString(falseStrings = { "no", "n", "null" }, trueStrings = { "yes", "y" })
    @Parsed
    private Boolean pending;
}

下面介绍如何获取列表TestBean

BeanListProcessor<TestBean> rowProcessor = new BeanListProcessor<TestBean>(TestBean.class);

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);
parser.parse(getReader("/examples/bean_test.csv"));

List<TestBean> beans = rowProcessor.getBeans();

披露:我是这个库的作者。它是开源和免费的(Apache V2.0许可证)。