开发者

OpenCSV date parse

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 Open开发者_运维问答JPA 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.


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
}


Alternatively, you could use Super CSV, which has a cell processor API which would allow you to read the bean (without modifications) using the ParseDate processor for that column.


Maybe a transient setter method alongside the original would work for you:

@Transient
public void setDate(String date) {
   Date d = parseDate(date);
   setDate(d);
}

@Column
public void setDate(Date date) {
  this.date = date;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜