0

I am creating an endpoint that, gets parameters:

  • a CSV file
  • name of a class (that I will use to create an instance of)

In mapping I am using CommonsCSV library.

Although I am getting CSVRecord I couldn't map it to an instance of the class I got as a parameter.

Example: as A parameter I got:-

  • CSV
id firstName lastName
1 John Rodriguez
2 Michael Hernandez
3 David Smith
  • className

    'employee'

// employee class
Class<?> classType = Class.forName(className);

// CSV file records
List<CSVRecord> records = csvParser.getRecords();

for (int i = 0; i < records.size(); i++) {
     CSVRecord record = records.get(i);
     // I want to get an instance of employee to save it to database like this
     {
      "id" : 1,
      "firstName" : "John",
      "lastName"  : "Rodriguez"
     }
   }

Thanks in advance!

  • I'm not sure Commons CSV supports mapping records to arbitrary classes or even json like you seem to want. One way you could try is `record.toMap()` which you could then convert to json using a Jackson or any similar library. One caveat with this might be that "id" would then have the type `String`. You could try to use Jackson to also convert the map to your employee class (it basically converts map->json->employee) and might be able to do the `String` -> `int` conversion along the way. – Thomas Jan 11 '23 at 07:13
  • [Duplicate question without an answer, because no solution really exists](https://stackoverflow.com/questions/72689135/csvtobean-equivalent-for-apache-commons-csv) – XtremeBaumer Jan 11 '23 at 07:14
  • Thanks guys, I'm now believing that there no actual answer for my problem. So I am mapping it my self now – Moaaz Gaballah Jan 19 '23 at 06:46

1 Answers1

0

I think Super CSV can help you, detail you can check this doc. Super CSV

private static void readWithCsvBeanReader() throws Exception {
        
        ICsvBeanReader beanReader = null;
        try {
                beanReader = new CsvBeanReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
                
                // the header elements are used to map the values to the bean (names must match)
                final String[] header = beanReader.getHeader(true);
                final CellProcessor[] processors = getProcessors();
                
                CustomerBean customer;
                while( (customer = beanReader.read(CustomerBean.class, header, processors)) != null ) {
                        System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(),
                                beanReader.getRowNumber(), customer));
                }
                
        }
        finally {
                if( beanReader != null ) {
                        beanReader.close();
                }
        }
}
HKBN-ITDS
  • 609
  • 1
  • 6