使用SimpleFlatMapper sfm-csv 6.0.3
|------|-------------|----------------|----------------|------------------|
| name | reference # | pf.first thing | pf.secondThing | pf.another.thing |
|======|=============|================|================|==================|
| foo | eb2e23c0d6a | a value here | | another value |
|------|-------------|----------------|----------------|------------------|
| bar | 0a4bba4c1d0 | values | all | throughout |
|------|-------------|----------------|----------------|------------------|
class Item {
private String name;
private String reference;
private Map<String, String> prefixedFields;
// ... builder, getters, etc.
}
final CsvMapper<Item> mapper = CsvMapperFactory.newInstance()
.addAlias("name", "itemName")
.addAlias("reference #", "reference")
.newMapper(Item.class);
return CsvParser.mapWith(mapper)
.stream(file, items -> items.collect(List.collector()));
现状是,Map
返回了null
。我正在尝试达到(伪代码):
firstRowItem.getPrefixedFields() == ImmutableMap.of(
"first thing", "a value here",
"another.thing", "another value")
secondRowItem.getPrefixedFields() == ImmutableMap.of(
"first thing", "values",
"secondThing", "all",
"another.thing", "throughout")
“ pf”。前缀是固定的,如果属性被命名为“ pf”,则一切正常:
class Item {
// ...
private Map<String, String> pf;
// ...
}
但是我希望将该属性命名为“ prefixedFields”,而不是“ pf”。
Map
的别名:.addColumnProperty(
col -> col.getName().startsWith("pf."),
MapTypeProperty.KEY_VALUE)
.addAlias
仅接受String
参数,因此这样的操作无效:.addAlias("pf.", "prefixedFields")
答案 0 :(得分:1)
A comment on a GitHub issue from the project owner使我步入正轨。
addColumnProperty
接受Object
的变量。您可以传入RenameProperty
,该参数可以接受String
参数以进行简单的列重命名,也可以接受Function<String, String> renameFunction
。像这样将它们放在一起:
final CsvMapper<Item> mapper = CsvMapperFactory.newInstance()
.addAlias("name", "itemName")
.addAlias("reference #", "reference")
.addColumnProperty(
column -> column.getName().startsWith("pf."),
new RenameProperty(columnName -> columnName.replace("pf.", "prefixedFields_")))
.newMapper(Item.class);