gpt4 book ai didi

java - OpenCSV 扁平化到层次结构数据解析

转载 作者:行者123 更新时间:2023-11-30 05:43:28 26 4
gpt4 key购买 nike

我需要有关在 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;
}

最佳答案

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 许可证)

关于java - OpenCSV 扁平化到层次结构数据解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55260431/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com