簡體   English   中英

將 CSVRecord 映射到我擁有的 class 實例

[英]Mapping a CSVRecord to instance of class that I have

我正在創建一個獲取參數的端點:

  • 一個 CSV 文件
  • class 的名稱(我將使用它來創建實例)

在映射中,我使用的是 CommonsCSV 庫。

盡管我正在獲取CSVRecord ,但我無法將其 map 轉換為我作為參數獲得的 class 的實例。

示例:作為參數,我得到了:-

  • CSV
ID
1個 約翰 羅德里格斯
2個 邁克爾 埃爾南德斯
3個 大衛 史密斯
  • 班級名稱

    '員工'

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

提前致謝!

我想超級 CSV 可以幫助你,詳細信息你可以查看這個文檔。 超級 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();
                }
        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM