Search code examples
javacsvparsingjavafxopencsv

How to import a csv with OpenCSV to FX SimpleObjectProperties?


For a school assignment, I need to parse a CSV into a Bean and present it in a JavaFX GUI later. I decided to use the Library opencsv, which worked fine.

But now, I would like to parse the attributes directly into SimpleObjectProperties. How do I do that? Unfortunately, I couldn't find any further information.

Code looks like this:

public class Phone {

@CsvBindByName(column = "ENTITY_ID")
private SimpleIntegerProperty entityId;

@CsvBindByName(column = "OPERATING_COMPANY")
private SimpleStringProperty operatingCompany;

When I run the code, I get a CsvDataTypeMismatchException (Conversion of 1006 to javafx.beans.property.SimpleIntegerProperty failed). Any help much appreciated, thank you!!


Solution

  • Looking at the documentation it looks like you can create CustomConverts for each type of property you have; the example they have on the documentation page, this is the start to an IntegerPropertyConverter.

    public class IntegerPropertyConverter extends AbstractCsvConverter {
    
       @Override
       public Object convert(String value) {
           return new SimpleIntegerProperty(Integer.parseInt(value));
       }
    
       @Override
       public String convertToWrite(Object value) {
           IntegerProprety prop = (IntegerProperty) value;
           return String.format("%d", prop.get());
       }
    
     }
    

    Then you'd use:

    @CsvCustomBindByName(column = "ENTITY_ID", converter = IntegerPropertyConverter.class)
    private SimpleIntegerProperty entityId;
    

    If you need to create your properties using the longer format, you will need to override other methods in the AbstractBeanField, such as public final void setFieldValue(T bean, String value, String header) where you can actually use the bean to create the