2016-10-03 8 views
1

java.sql.Dateフィールドを読み込み、Univocityを使用して次のように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);

でラインを解析するとき、私はcom.univocity.parsers.common.DataProcessingException: Error converting value 'Sat Apr 12 00:00:00 CEST 1986' using conversion com.univocity.parsers.conversions.TrimConversionの追加情報で、次の例外Caused by: java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.Stringを取得しています"12-04-1986"と私は変換を提供しようとしました "dd-MM-yyyy"、残念ながら無駄に。

「誕生日:12-04-1986」の予定されたメッセージを得るために私のコードには何が欠けていますか?

EDIT:java.util.Date

人のクラスを使用して:

// 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 
} 

java.util.DateにDateオブジェクトを変更し、上の正しい日付形式を適用しますjava.util.Dateオブジェクトが正常に印刷されていることを示します。

答えて

2

最初の問題は、あなたが定義した変換シーケンスです:

Conversions.toDate("dd-MM-yyyy"), Conversions.trim() 

これはDateオブジェクトを生成し、あなただけの得たエラーの原因となる代わりにStringの日付の上にString.trim()操作を、適用します。

あなたは、これは動作するはずの順序を変更する場合:

Conversions.trim(), Conversions.toDate("dd-MM-yyyy") 

しかし、あなたのPersonクラスがそうでなければ、nullを得るでしょう@Parsedで注釈を付けてbirthDateフィールドを持っている必要があります。

注釈をbirthDateフィールドに追加するのは、その一連の変換を適用するのではなく、簡単です。あなたはこのようなあなたのクラスを宣言することができます。

public class Person{ 
    @Parsed 
    String id; 

    @Parsed 
    String name; 

    @Parsed 
    @Format(formats = "dd-MM-yyyy") //notice that multiple formats are supported 
    Date birthDate; 
} 

最後に、あなたが設定でトリミング無効にしない限り、あなたがトリム変換や@Trimアノテーションを使用する必要はありませんので、パーサは、デフォルトで値をトリミングすることを気づきます。

これが役に立ちます。

+0

'あなたのbirthDateに@Formatアノテーションを追加する方が簡単なはずです。正確には私が存在することを望んでいた機能です。私はgithubのマニュアルには見つかりませんでしたが、この機能では、解析される実際のファイルには多くの日付オブジェクトがあり、その中には異なるフォーマットがあるため、日付解析が使いやすくなっています。今私は何を探すべきか分かっているので、 'AnotherTestBean.java'の例も見つけました。説明と助けてくれてありがとう! –

関連する問題