1

I want to make a utility class for mapping CSV format file to Object of given type. Is there any library to map from String values to whole object?

I have this part of code:

public static List<?> mapCsvToListOfType(File file, Class<?> className) throws IOException {
        CSVParser parse = CSVParser.parse(file, StandardCharsets.US_ASCII, CSVFormat.DEFAULT);
        ObjectMapper mapper = new ObjectMapper();
        
        return parse.getRecords().stream()
                .map(x -> mapper.convertValue(x, className))
                .collect(Collectors.toList());
    }

Of course that doesn't work because x is String type and mapper don't recognise String.class fields in Product.class;

CSVParser returns CSVRecords which contains Strings from csv. Now I want to map it like this (example):

mapCsvToListOfType(new File("products.csv"), Product.class);

CSVRecord returns this when printed:

[CSVRecord [comment='null', recordNumber=1, values=[external_id,  producer_part_number,  name,  eancode,  vendor,  final_price,  price,  list_price,  currency]]

How to do it in generic way to be universal? Should I change Apache Commons CSV to something else?

MrFisherman
  • 720
  • 1
  • 7
  • 27

0 Answers0