简体   繁体   English

使用jackson-dataformat-csv从CSV解析双引号

[英]Parsing double quote with new line from CSV using jackson-dataformat-csv

I have the following CSV format:我有以下 CSV 格式:

id,name,description,age
23,Anna,"Self-made
Chef
Shoemaker",23

The double-quotes are only present if the attribute is multi-line.仅当属性是多行时才存在双引号。 While I am already been able to read the normal CSV correctly:虽然我已经能够正确读取正常的 CSV :

@Bean
public CsvMapper csvMapper() {
    CsvMapper csvMapper = new CsvMapper();
    csvMapper.registerModule(new JavaTimeModule());
    csvMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return csvMapper;
}

I tried adding a new feature:我尝试添加一个新功能:

csvMapper.configure(Feature.FAIL_ON_MISSING_COLUMNS, true);

But it makes the library skip failed rows.但它使库跳过失败的行。 How do I parse the given format and get the whole Self-made\n Chef\n Shoemaker into the description attribute?如何解析给定的格式并将整个Self-made\n Chef\n Shoemaker放入描述属性中?

According to my reading of the code in the CSVDecoder class ( link ), the Jackson CSV parser in version 2.14 will correctly parse double-quoted strings that have embedded line-breaks.根据我对CSVDecoder class ( 链接) 中代码的阅读,Jackson CSV 2.14 版中的解析器将正确解析嵌入的双引号字符串。 Look for the _nextQuotedString method.寻找_nextQuotedString方法。 No attribute needs to be set to enable this.无需设置任何属性即可启用此功能。 It happens unconditionally.它无条件地发生。

Indeed, it looks like the relevant lines of the code have not changed in at least 5 years.事实上,看起来代码的相关行至少在 5 年内没有改变。

So... if the CSV parser is not working for you (without that Feature ), my diagnosis is:所以......如果 CSV 解析器不适合你(没有那个Feature ),我的诊断是:

  • either you are using a really old version of Jackson,要么您使用的是真正旧版本的 Jackson,
  • or the apparently incomplete values you are seeing are injected somewhere / somehow after CSV parsing.或者您看到的明显不完整的值在 CSV 解析之后以某种方式注入。

If this doesn't solve your problem, please add a minimal reproducible example to the Question, and tell us the version(s) of the Jackson dependencies you are using.如果这不能解决您的问题,请在问题中添加一个最小的可重现示例,并告诉我们您正在使用的 Jackson 依赖项的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM