将CSVRecordMap到类的示例

zzoitvuj  于 2023-01-15  发布在  其他
关注(0)|答案(1)|浏览(77)

我正在创建一个端点,它获取参数:

  • CSV文件
  • 类的名称(我将使用它来创建示例)

在Map中,我使用CommonsCSV库。
虽然我得到了CSVRecord,但我无法将其Map到作为参数得到的类的示例。
例如:作为一个参数,我得到:-

  • CSV语言

| 身份证|名字|姓氏|
| - ------|- ------|- ------|
| 1个|约翰|罗德里格斯|
| 第二章|迈克尔|埃尔南德斯|
| 三个|大卫|史密斯|

  • 类名

“雇员”

// 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"
     }
   }

先谢了!

ztmd8pv5

ztmd8pv51#

我想Super CSV可以帮到你,详细的你可以查看这个文档。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();
                }
        }
}

相关问题