为什么在使用 LocalDate 作为 POJO 的数据类型时 univocity 的 CsvParser 抛出错误以及如何重新爱它?

Why univocity's CsvParser throwing error when use LocalDate as the datatype for POJO and How to reslove it?

我正在使用 Univocity 的 CSVParser 读取 csv 文件。我的 POJO 看起来像这样。

import java.time.LocalDate;
import com.univocity.parsers.annotations.NullString;
import com.univocity.parsers.annotations.Parsed;
import lombok.Builder;
import lombok.Getter;

@Getter
@Setter
public class TempClass {

    @Parsed(field = "A")
    private int a;

    @Parsed(field = "B")
    private String b;

    @Parsed(field = "C")
    private LocalDate c;
}

我的 csv 文件看起来像这样:-

A,B,C
1,"Hi","2019-01-12"
2,"Hey","2019-01-13"
3,"Hello","2019-01-14"

现在,当我尝试使用 CsvParser 读取此文件时,它会抛出错误 Unable to set value '2019-01-12' of type 'java.lang.String' to field attribute 'c'

这里我猜它是抛出错误,因为它不能隐式地将String转换为LocalDate。如果是这样,那么如何将 String 转换为 int

有没有办法解决错误Unable to set value '2019-01-12' of type 'java.lang.String' to field attribute 'c'?(不改变TempClass.c的数据类型)

Univocity-parsers 仍然建立在 Java6 上。LocalDate 不直接支持开箱即用,但可以自己提供转换。类似于:

public class LocalDateFormatter implements  Conversion<String, LocalDate> {

    private DateTimeFormatter formatter;

    public LocalDateFormatter(String... args) {
        String pattern = "dd MM yyyy";
        if(args.length > 0){
            pattern = args[0];
        }
        this.formatter = DateTimeFormatter.ofPattern(pattern);
    }

    @Override
    public LocalDate execute(String input) {
        return LocalDate.parse(input, formatter);
    }

    @Override
    public String revert(LocalDate input) {
        return formatter.format(input);
    }
}

然后用 @Convert 注释您的字段并提供您的转换 class:"

@Parsed(field = "C")
@Convert(conversionClass = LocalDateFormatter.class, args = "yyyy-MM-dd")
private LocalDate c;

下一版本 (3.0.0) 即将推出,支持此功能以及更多功能。

希望对您有所帮助。