我有需要解析的CSV
文件。该文件的架构如下:
名称,联系人-每个人的联系人都有很多字符串
此联系人列的数量不规则。
例如:
john, [email protected], 123 123 123, fb/john.wick
mike, 123 0303 11
dave,
我正在尝试为我的bean创建一个带有
CsvSchema
的Jacskon CSV
:public class Person {
private String name;
private String[] contacts;
}
通过创建自定义架构:
CsvSchema schema = CsvSchema.builder()
.addColumn("name")
.addArrayColumn("contacts", ",")
.build();
但是我得到这个:
com.fasterxml.jackson.dataformat.csv.CsvMappingException: Too many entries: expected at most 2
如何用
Jackson CSV
解决这样的问题?Java
代码:CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.builder()
.addColumn("name")
.addArrayColumn("contacts", ",")
.build();
MappingIterator<Person> it = mapper.readerFor(Person.class).with(schema)
.readValues(csvString);
List<Person> all = it.readAll();
最佳答案
您可以使用CsvParser.Feature.WRAP_AS_ARRAY功能并将整个行读取为List<String>
。在构造函数中,您可以将List
转换为Person
对象。请参见以下示例:
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvParser;
import java.io.File;
import java.util.List;
import java.util.stream.Collectors;
public class CsvApp {
public static void main(String[] args) throws Exception {
File csvFile = new File("./resource/test.csv").getAbsoluteFile();
CsvMapper csvMapper = new CsvMapper();
csvMapper.enable(CsvParser.Feature.WRAP_AS_ARRAY);
MappingIterator<List<String>> rows = csvMapper.readerFor(List.class).readValues(csvFile);
List<Person> persons = rows.readAll().stream()
.filter(row -> !row.isEmpty())
.map(Person::new)
.collect(Collectors.toList());
persons.forEach(System.out::println);
}
}
class Person {
private String name;
private List<String> contacts;
public Person(List<String> row) {
this.name = row.remove(0);
this.contacts = row;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getContacts() {
return contacts;
}
public void setContacts(List<String> contacts) {
this.contacts = contacts;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", contacts=" + contacts +
'}';
}
}
对于您的输入,上面的代码打印如下:
Person{name='john', contacts=[[email protected], 123 123 123, fb/john.wick]}
Person{name='mike', contacts=[123 0303 11]}
Person{name='dave', contacts=[]}