如何使用SimpleFlatMapper将带前缀的CSV列别名到地图?

时间:2019-04-05 18:42:58

标签: java csv simpleflatmapper

背景

使用SimpleFlatMapper sfm-csv 6.0.3

示例CSV:

|------|-------------|----------------|----------------|------------------|
| name | reference # | pf.first thing | pf.secondThing | pf.another.thing |
|======|=============|================|================|==================|
| foo  | eb2e23c0d6a | a value here   |                | another value    |
|------|-------------|----------------|----------------|------------------|
| bar  | 0a4bba4c1d0 | values         | all            | throughout       |
|------|-------------|----------------|----------------|------------------|

Pojo

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”。

尝试解决问题

.addColumnProperty(
    col -> col.getName().startsWith("pf."),
    MapTypeProperty.KEY_VALUE)
  • .addAlias仅接受String参数,因此这样的操作无效:
.addAlias("pf.", "prefixedFields")

1 个答案:

答案 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);