【问题标题】:Jackson CSV missing columnsJackson CSV 缺少列
【发布时间】:2015-08-26 19:28:00
【问题描述】:

我正在使用Jackson CSV 将 CSV 文件解析为 POJO。我的问题是,如果 CSV 中的一行的列太少,解析器不会抱怨,只会将其余字段设置为 null。

解析代码:

    CsvMapper csvMapper = new CsvMapper();
    csvMapper.addMixInAnnotations(Person.class, PersonCsvMixin.class);
    CsvSchema schema = csvMapper.schemaFor(Person.class).withHeader();
    MappingIterator<Person> it = csvMapper.reader(dataClass).with(schema).readValues(csv);
    LinkedList<Person> output = new LinkedList<>();

    while(it.hasNext()) {
        output.push(it.next());
    }

混音:

import com.fasterxml.jackson.annotation.*;

@JsonPropertyOrder(value = { "FirstName", "LastName", "Title"})
public abstract class Person {
    @JsonProperty("LastName")
    public abstract String getLastName();
    @JsonProperty("FirstName")
    public abstract String getFirstName();
    @JsonProperty("Title")
    public abstract String getTitle();
}

数据类:

public class OfficespaceInputEmployee implements Serializable{
    protected String firstName;
    protected String lastName;
    protected String title;
    // .. getters and setters
}

如果我解析如下文件,即使中间记录缺少两个字段,也不会发生错误。相反,LastName 和 Title 变为 null

"FirstName", "LastName", "Title"
"John", "Smith", "Mr"
"Mary"
"Peter", "Jones", "Dr"

是否有启用会导致此错误的功能?

【问题讨论】:

  • 显示您的 MappingIterator 使用情况。
  • @LaurentiuL。添加了 MappingIterator 用法

标签: java parsing csv jackson


【解决方案1】:

我知道这是一个旧线程,但是当我自己遇到同样的问题时,让我分享一下解决方案:

csvMapper.configure(CsvParser.Feature.FAIL_ON_MISSING_COLUMNS, true); 可以解决问题。

【讨论】:

  • 我有这个不错的设置: myObjectReader = csvMapper .readerFor(Map.class) .with(csvSchema) .without(IGNORE_TRAILING_UNMAPPABLE) .without(ALLOW_TRAILING_COMMA) .with(FAIL_ON_MISSING_COLUMNS);
【解决方案2】:

在里面构建输出LinkedList的时候可以自己抛出异常 while 循环:

while(it.hasNext()) {
    Person line = it.next();
    //call a method which checks that all values have been set 
    if (thatMethodReturnsTrue){
        output.push(line);
    } else{
      throw SomeException();
    }
}

【讨论】:

  • 好的,谢谢。我知道我可以这样做,但我希望库会在解析时实际检查它,就像在字段太多时那样。
  • 我没有找到任何你可以传递的选项来使解析器变得严格。我想可能没有
  • @rewolf 拥有一个可以在 CsvMapper 上启用的 CsvParser.Feature 会很有用。您可以在 github 上添加建议
  • CsvMapper 的基类 ObjectMapper 有一个 configure 方法,它有一些有用的配置,但我认为它不适用于 csv 解析器。为 csv 解析与反序列化类似的功能会很有用: csvMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, false)
  • 目前库中没有办法做到这一点,所以我会在迭代时添加检查,并将其标记为答案。谢谢:)
【解决方案3】:

我建议为问题跟踪器提交 RFE,例如 CsvParser.Feature.REQUIRE_ALL_COLUMNS:如果启用,解析器将抛出异常以指示缺少一个或多个预期列。 这听起来对我很有用。

【讨论】:

猜你喜欢
  • 2022-01-25
  • 1970-01-01
  • 2022-08-14
  • 1970-01-01
  • 2020-11-18
  • 2018-02-23
  • 2022-01-04
  • 2015-12-05
  • 1970-01-01
相关资源
最近更新 更多