我正在尝试使用Univocity读取java.sql.Date字段并将其解析为java bean代码:java.lang.ClassCastException:使用Univocity时,java.util.Date不能转换为java.lang.String
public class Example {
public static void main(final String[] args) throws FileNotFoundException {
final BeanListProcessor<Person> rowProcessor = new BeanListProcessor<Person>(Person.class);
final CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(false);
parserSettings.getFormat().setDelimiter('|');
final String line = "0|John|12-04-1986";
final CsvParser parser = new CsvParser(parserSettings);
parser.parseLine(line);
final List<Person> beans = rowProcessor.getBeans();
for (final Person person : beans) {
// Expected print: Birthday: 12-04-1986
System.out.println("Birthday: " + person.getBirthDate());
}
}
}
但parser.parseLine(line);
我想代表日期到它是如何在线路如解析线的时候,我收到以下异常Caused by: java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String
与com.univocity.parsers.common.DataProcessingException: Error converting value 'Sat Apr 12 00:00:00 CEST 1986' using conversion com.univocity.parsers.conversions.TrimConversion
其他信息“12-04-1986”,我尝试提供转换“dd-MM-yyyy”,遗憾的是无济于事。
我在代码中错过了什么以获得期望的“生日:12-04-1986”系统?
编辑:使用java.util.Date
Person类:
// using the correct Date object!
import java.util.Date;
import com.univocity.parsers.annotations.Format;
import com.univocity.parsers.annotations.Parsed;
public class Person {
@Parsed(index=0)
private Integer id;
@Parsed(index=1)
private String name;
@Parsed(index=2)
@Format(formats = "dd-MM-yyyy")
private Date birthDate;
//getters and setters ommited
}
当改变Date对象的java.util.Date和对应用正确的日期格式java.util.Date对象的打印正确显示预期的结果。
'应该更容易在您的birthDate上添加@Format注释,正是我希望能够呈现的功能。我在github的手册中找不到它,但是这个特性使日期解析更加容易,因为解析的实际文件有很多日期对象,而且其中一些有不同的格式。现在我知道该找什么了,我也找到了'AnotherTestBean.java'的例子。感谢您的解释和帮助! –