我尝试用openCSV映射嵌套的bean结构。我找到了@CsvRecurse注释,但是如果多次使用嵌套bean,这似乎不起作用。
我有什么办法解决这个问题?
示例(改编自上面链接的文档)
地图的数据结构:
title,author1 given name,author1 surname,author2 given name,author2 surname
Space Opera 2.0,Andrew,Jones,Hanna,Smith我想买以下豆子
public class Book {
@CsvBindByName
private String title;
// TODO: How to bind author1 and author2?
private Author author1;
private Author author2;
// Accessor methods go here.
}
public class Author {
// TODO: can I somehow use a prefix/Regex for the column here to differentiate between author1 and author2?
@CsvBindByName(column = "author[1/2] given name")
private String givenName;
@CsvBindByName(column = "author[1/2] surname")
private String surname;
// Accessor methods go here.
}发布于 2020-06-13 21:28:50
以下是另一种选择:
opencsv库有很多有用和灵活的注释,但是在这个特定的例子中,我不会使用其中的任何一个。
相反,我会使用opencsv CSVReaderHeaderAware类。使用这将允许您保留两个Book和Author类。我要更改的惟一方法是将构造函数添加到每个类中,如下所示:
书籍:
public class Book {
private final String title;
private final Author author1;
private final Author author2;
public Book(String title, Author author1, Author author2) {
this.title = title;
this.author1 = author1;
this.author2 = author2;
}
public String getTitle() {
return title;
}
public Author getAuthor1() {
return author1;
}
public Author getAuthor2() {
return author2;
}
}作者:
public class Author {
private final String givenName;
private final String surname;
public Author(String givenName, String surname) {
this.givenName = givenName;
this.surname = surname;
}
public String getGivenName() {
return givenName;
}
public String getSurname() {
return surname;
}
}要从CSV文件中填充Book对象的列表,请执行以下操作:
import java.util.Map;
import java.util.List;
import java.util.ArrayList;
import com.opencsv.CSVReaderHeaderAware;
import com.opencsv.exceptions.CsvValidationException;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
...
public static void main(String[] args) throws FileNotFoundException,
IOException, CsvValidationException {
String bookFile = "/path/to/titles.csv";
CSVReaderHeaderAware csvReader = new CSVReaderHeaderAware(new FileReader(bookFile));
List<Book> books = new ArrayList();
Map<String, String> bookRecord;
while ((bookRecord = csvReader.readMap()) != null) {
books.add(handleBook(bookRecord));
}
}
private static Book handleBook(Map<String, String> bookRecord) {
Author author1 = new Author(
bookRecord.get("author1 given name"),
bookRecord.get("author1 surname")
);
Author author2 = new Author(
bookRecord.get("author2 given name"),
bookRecord.get("author2 surname")
);
return new Book(bookRecord.get("title"), author1, author2);
}CSV文件中的每一行数据都被读取到一个Map对象中,其中文件头是映射的键(您需要确保文件头是唯一的)。Map的对应值表示CSV文件中的一行数据。
唯一的缺点是,您可能需要将字符串值转换为其他数据类型--尽管在这种情况下不是这样,因为数据项已经是字符串了。
https://stackoverflow.com/questions/62281443
复制相似问题