OpenCSV平面到层次结构数据解析

时间:2019-03-20 12:08:23

标签: java csv opencsv

我需要在解析Java中的CSV数据时遇到的问题的建议。

我有一个CSV文件,其中的数据格式如下

name, gender, address_first_line, address_second_line, city, number 
me, Male, anonymous, random, Auckland, 6545
other, Female, random, anon, Auckland, 6688

我想使用对象模型下面的openCSV库解析CSV文件。我知道解析单个类,但是当涉及多个类时解析数据时会遇到问题。请建议是否有其他可用的库可以帮助我获得所需的结果。

Class User {
    String name;
    String gender;
    Address address;
    long number;
}

Class Address {
   String firstLine;
   String secondLine;
}

1 个答案:

答案 0 :(得分:1)

univocity-parsers具有@Nested注释,您可以使用:

尝试一下:

public static class User {
    @Parsed
    String name;
    @Parsed
    String gender;
    @Nested
    Address address;
    @Parsed
    long number;

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", address=" + address +
                ", number=" + number +
                '}';
    }
}

public static  class Address {
    @Parsed(field = "address_first_line")
    String firstLine;
    @Parsed(field = "address_second_line")
    String secondLine;

    @Override
    public String toString() {
        return "Address{" +
                "firstLine='" + firstLine + '\'' +
                ", secondLine='" + secondLine + '\'' +
                '}';
    }
}

public static void main(String ... args){
    StringReader input = new StringReader(
            "name,gender,address_first_line,address_second_line, city,number\n" +
            "John,M,Somewhere,Else,City,1");


    for(User user : new CsvRoutines().iterate(User.class, input)){
        System.out.println(user.toString());
    }

}

输出:

User{name='John', gender='M', address=Address{firstLine='Somewhere', secondLine='Else'}, number=1}

如果您不喜欢注释,则可以手动映射内容:

    CsvRoutines routines = new CsvRoutines();
    ColumnMapper mapper = routines.getColumnMapper();

    mapper.attributeToColumnName("name", "name");
    mapper.attributeToColumnName("gender", "gender");
    mapper.attributeToColumnName("number", "number");
    mapper.attributeToColumnName("address.firstLine", "address_first_line");
    mapper.attributeToColumnName("address.secondLine", "address_second_line");

    for (User user : routines.iterate(User.class, input)) {
        System.out.println(user.toString());
    }

希望有帮助。

免责声明:我是这个库的作者。它是开源且免费的(Apache 2.0许可证)