您当然可以使用 Super CSV 实现这一目标。
您可以使用
使用 CsvBeanReader
如果您不想使用 Dozer 并且能够修改您的 bean 类,最简单的选择是在您的 bean 上添加一个虚拟设置器,CsvBeanReader
用于填充属性。我假设您的Person
和PersonAttribute
bean 有一个公共的无参数构造函数和为每个字段定义的 getter/setter(这是必需的)。
将以下虚拟设置器添加到您的Person
bean:
public void setAddAttribute(PersonAttribute attribute){
if (attribs == null){
attribs = new ArrayList<PersonAttribute>();
}
attribs.add(attribute);
}
创建一个自定义单元处理器,它将PersonAttribute
使用 CSV 标题中的适当键和 CSV 列中的值填充 a。
package org.supercsv.example;
import org.supercsv.cellprocessor.CellProcessorAdaptor;
import org.supercsv.util.CsvContext;
/**
* Creates a PersonAttribute using the corresponding header as the key.
*/
public class ParsePersonAttribute extends CellProcessorAdaptor {
private final String[] header;
public ParsePersonAttribute(final String[] header) {
this.header = header;
}
public Object execute(Object value, CsvContext context) {
if( value == null ) {
return null;
}
PersonAttribute attribute = new PersonAttribute();
// columns start at 1
attribute.setKey(header[context.getColumnNumber() - 1]);
attribute.setValue((String) value);
return attribute;
}
}
我认为以下示例主要说明了问题,但我应该指出以下几点:
我必须使用自定义首选项,因为您的 CSV 包含不属于数据的空格
我必须动态组装字段映射和单元处理器数组,因为您的数据具有未知数量的属性(此设置通常不那么复杂)
属性使用的所有字段映射addAttribute
,对应于setAddAttribute()
我们添加到您的 bean 的方法
我已经使用我们的自定义单元处理器PersonAttribute
为每个属性列创建了一个 bean
这是代码:
package org.supercsv.example;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
public class ReadWithCsvBeanReader {
private static final String CSV =
"firstname, lastname, dog_name, fav_hat, fav_color\n"
+ "bill,smith,fido,porkpie,blue\n"
+ "james,smith,rover,bowler,purple";
private static final String CSV2 =
"firstname, lastname, car_type, floor_number\n"
+ "tom, collins, ford, 14\n" + "jim, jones, toyota, 120";
// attributes start at element 2 of the header array
private static final int ATT_START_INDEX = 2;
// custom preferences required because CSV contains
spaces that aren't part of the data
private static final CsvPreference PREFS =
new CsvPreference.Builder(
CsvPreference.STANDARD_PREFERENCE)
.surroundingSpacesNeedQuotes(true).build();
public static void main(String[] args) throws IOException {
System.out.println("CsvBeanReader with first CSV input:");
readWithCsvBeanReader(new StringReader(CSV));
System.out.println("CsvBeanReader with second CSV input:");
readWithCsvBeanReader(new StringReader(CSV2));
}
private static void readWithCsvBeanReader(final Reader reader)
throws IOException {
ICsvBeanReader beanReader = null;
try {
beanReader = new CsvBeanReader(reader, PREFS);
final String[] header = beanReader.getHeader(true);
// set up the field mapping and processors dynamically
final String[] fieldMapping = new String[header.length];
final CellProcessor[] processors =
new CellProcessor[header.length];
for (int i = 0; i < header.length; i++) {
if (i < ATT_START_INDEX) {
// normal mappings
fieldMapping[i] = header[i];
processors[i] = new NotNull();
} else {
// attribute mappings
fieldMapping[i] = "addAttribute";
processors[i] =
new Optional(new ParsePersonAttribute(header));
}
}
Person person;
while ((person = beanReader.read(Person.class, fieldMapping,
processors)) != null) {
System.out.println(String.format(
"lineNo=%s, rowNo=%s, person=%s",
beanReader.getLineNumber(), beanReader.getRowNumber(),
person));
}
} finally {
if (beanReader != null) {
beanReader.close();
}
}
}
}
输出(我toString()
在你的 bean 中添加了方法):
CsvBeanReader with first CSV input:
lineNo=2, rowNo=2, person=Person [firstname=bill, lastname=smith, attribs=[PersonAttribute [key=dog_name, value=fido], PersonAttribute [key=fav_hat, value=porkpie], PersonAttribute [key=fav_color, value=blue]]]
lineNo=3, rowNo=3, person=Person [firstname=james, lastname=smith, attribs=[PersonAttribute [key=dog_name, value=rover], PersonAttribute [key=fav_hat, value=bowler], PersonAttribute [key=fav_color, value=purple]]]
CsvBeanReader with second CSV input:
lineNo=2, rowNo=2, person=Person [firstname=tom, lastname=collins, attribs=[PersonAttribute [key=car_type, value=ford], PersonAttribute [key=floor_number, value=14]]]
lineNo=3, rowNo=3, person=Person [firstname=jim, lastname=jones, attribs=[PersonAttribute [key=car_type, value=toyota], PersonAttribute [key=floor_number, value=120]]]
使用 CsvDozerBeanReader
如果您不能或不想修改您的 bean,那么我建议CsvDozerBeanReader
在Super CSV Dozer Extension项目中使用,因为它支持嵌套和索引字段映射。看看这里使用的一些例子。
下面是一个使用CsvDozerBeanReader
. 您会注意到它与CsvBeanReader
示例几乎相同,但是:
代码:
package org.supercsv.example;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.supercsv.cellprocessor.Optional;
import org.supercsv.cellprocessor.constraint.NotNull;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.io.dozer.CsvDozerBeanReader;
import org.supercsv.io.dozer.ICsvDozerBeanReader;
import org.supercsv.prefs.CsvPreference;
public class ReadWithCsvDozerBeanReader {
private static final String CSV =
"firstname, lastname, dog_name, fav_hat, fav_color\n"
+ "bill,smith,fido,porkpie,blue\n"
+ "james,smith,rover,bowler,purple";
private static final String CSV2 =
"firstname, lastname, car_type, floor_number\n"
+ "tom, collins, ford, 14\n"
+ "jim, jones, toyota, 120";
// attributes start at element 2 of the header array
private static final int ATT_START_INDEX = 2;
// custom preferences required because CSV contains spaces that aren't part of the data
private static final CsvPreference PREFS = new CsvPreference.Builder(CsvPreference.STANDARD_PREFERENCE)
.surroundingSpacesNeedQuotes(true).build();
public static void main(String[] args) throws IOException {
System.out.println("CsvDozerBeanReader with first CSV input:");
readWithCsvDozerBeanReader(new StringReader(CSV));
System.out.println("CsvDozerBeanReader with second CSV input:");
readWithCsvDozerBeanReader(new StringReader(CSV2));
}
private static void readWithCsvDozerBeanReader(final Reader reader) throws IOException {
ICsvDozerBeanReader beanReader = null;
try {
beanReader = new CsvDozerBeanReader(reader, PREFS);
final String[] header = beanReader.getHeader(true);
// set up the field mapping, processors and hints dynamically
final String[] fieldMapping = new String[header.length];
final CellProcessor[] processors = new CellProcessor[header.length];
final Class<?>[] hintTypes = new Class<?>[header.length];
for( int i = 0; i < header.length; i++ ) {
if( i < ATT_START_INDEX ) {
// normal mappings
fieldMapping[i] = header[i];
processors[i] = new NotNull();
} else {
// attribute mappings
fieldMapping[i] = String.format("attribs[%d]", i - ATT_START_INDEX);
processors[i] = new Optional(new ParsePersonAttribute(header));
hintTypes[i] = PersonAttribute.class;
}
}
beanReader.configureBeanMapping(Person.class, fieldMapping, hintTypes);
Person person;
while( (person = beanReader.read(Person.class, processors)) != null ) {
System.out.println(String.format("lineNo=%s, rowNo=%s, person=%s",
beanReader.getLineNumber(),
beanReader.getRowNumber(), person));
}
}
finally {
if( beanReader != null ) {
beanReader.close();
}
}
}
}
输出:
CsvDozerBeanReader with first CSV input:
lineNo=2, rowNo=2, person=Person [firstname=bill, lastname=smith, attribs=[PersonAttribute [key=dog_name, value=fido], PersonAttribute [key=fav_hat, value=porkpie], PersonAttribute [key=fav_color, value=blue]]]
lineNo=3, rowNo=3, person=Person [firstname=james, lastname=smith, attribs=[PersonAttribute [key=dog_name, value=rover], PersonAttribute [key=fav_hat, value=bowler], PersonAttribute [key=fav_color, value=purple]]]
CsvDozerBeanReader with second CSV input:
lineNo=2, rowNo=2, person=Person [firstname=tom, lastname=collins, attribs=[PersonAttribute [key=car_type, value=ford], PersonAttribute [key=floor_number, value=14]]]
lineNo=3, rowNo=3, person=Person [firstname=jim, lastname=jones, attribs=[PersonAttribute [key=car_type, value=toyota], PersonAttribute [key=floor_number, value=120]]]
在整理这个示例时,我CsvDozerBeanReader
在 Super CSV 2.0.1 中发现了一个错误,当您将单元处理器(例如我在上面示例中创建的用于解析每个人属性键/值的处理器)与索引映射相结合时,例如:
"firstname","lastname","attribs[0]","attribs[1]"
我刚刚发布了修复此问题的 Super CSV 2.1.0。事实证明,Dozer 需要为索引映射配置一个提示才能正常工作。我不是 100% 确定为什么,因为PersonAttribute
当您摆脱自定义单元处理器并使用以下(深度)映射时,它非常有能力创建每个并将其添加到正确的索引中:
"firstname","lastname","attribs[0].value","attribs[1].value"
我希望这有帮助 :)