'How to convert field in opencsv correct?
I have csv file with this columns id,equity_name,field,date,quartal,year. I have java class where there is a field
@Column(
columnDefinition = "smallint"
)
@Convert(
converter = YearAttributeConverter.class
)
@CsvCustomBindByName(column = "year", converter = YearCsvConverter.class)
private Year year;
And i use custom converter for this field.
@NoArgsConstructor
public class YearCsvConverter extends AbstractBeanField {
@Override
protected Object convert(String value) throws CsvDataTypeMismatchException, CsvConstraintViolationException {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
return LocalDate.parse(value, formatter);
}
}
When i tried to parse file i have an
Exception in thread "pool-1-thread-6" java.lang.RuntimeException: com.opencsv.exceptions.CsvDataTypeMismatchException: Conversion of 1990-12-31 to java.time.LocalDate failed.
How to make this work and convert the field?
Solution 1:[1]
Your converter returns a LocalDate, but your field is of type Year, that is your DataTypeMismatch in the CsvDataTypeMismatchException.
Make your converter return an object of the correct data type e.g.:
return Year.fromLocalDate(LocalDate.parse(value, formatter));
On a side note: if you csvBindByName or CsvCustomBindByName, you don't need to specify the column name, and the following should work as long as your field name matches your header name.
@CsvCustomBindByName(converter = YearCsvConverter.class)
private Year year;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
