1

我正在使用 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'.

在这里我猜它会抛出错误,因为它不能隐式转换StringLocalDate. 如果是这种情况,那么它如何能够转换Stringint

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

4

1 回答 1

4

Univocity-parsers 仍然建立在 Java 6 之上。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并提供您的转换类:"

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

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

希望这可以帮助。

于 2019-04-04T01:15:09.453 回答