OpenCSV date parse

quantum picture quantum · Apr 30, 2011 · Viewed 8.2k times · Source

We're using OpenCSV to parse a CSV file and bind its values directly to a model object (OpenJPA entity bean) by using CsvToBean class.

However, the problem is - there are some values in CSV that are (obviously) parsed as Strings, but should be set in a Date property, so basically CsvToBean class dies while trying to dynamically invoke writing method (i.e., it tries to set a Date property with raw String value).

Is there any facility inside OpenCSV that would allow me to specify to which type should each column be mapped to? If not, do you have any suggestions what class to extend/reimplement in order to facilitate this? Inspecting other available strageties in OpenCSV source distribution under /test/au/com/bytecode/opencsv/bean/ directory got me no closer to conclusion.

I guess I could fiddle with the Date property setter and make it a generic method which would get the type being passed as argument, and try to parse the passed value into Date if it isn't Date already, but....we're using persistence annotated Entities and I have no wish to see later on that this "setter-hack" shot us in our foot because OpenJPA Enhancer suddenly disliked generic setter.

I've been bashing my head around this for a couple of hours - I could have probably solved the problem by using reflection and writing my own bean-binding logic, but I loathe re-inventing the wheel and have a feeling/hope this could be done somewhat easily inside the existing OpenCSV framework.

If needed, I could post some code, but there's really not much to see.

Any thoughts? Thx.

Answer

Kal picture Kal · Apr 30, 2011

How about creating a copy of the Date property in your class definition? We've done something similar using BeanUtils

So, your Bean class contains

String dateString;
Date date;

public void setDateString(String dateString) {
     // This method can parse the dateString and set date object as well
}

public void setDate(Date date) {
     // Use this for JPA
}