如何在Java中将csv文件映射到pojo类 [英] How to map csv file to pojo class in java

查看:102
本文介绍了如何在Java中将csv文件映射到pojo类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java maven插件.我想获取pojo类中的employee.csv文件记录.我从employee.csv标头生成的这个pojo类,并且pojo类的所有字段都是String类型.现在我想将employee.csv映射到生成的pojo类.我的要求是我不想手动指定列名.因为如果我更改csv文件,然后再次必须修改代码,以便它可以与任何文件动态映射.例如

I am using java maven plugin.I want to fetch employee.csv file records in pojo class. this pojo class I am generating from employee.csv header and all fields of pojo class are String type.now I want to map employee.csv to generated pojo class.my requirement is I dont want to specify column names manually.because if I change csv file then again I have to chane my code so it should dynamically map with any file. for instance

firstName,lastName,title,salary 
john,karter,manager,54372

我想将此映射到我已经拥有的pojo

I want to map this to pojo which I have already

public class Employee
{
  private String firstName;
  private String lastName;
  .
  .
  //getters and setters 
  //toString()
} 

推荐答案

uniVocity分析器使您可以轻松地映射pojo.

uniVocity-parsers allows you to map your pojo easily.

class Employee {

    @Trim
    @LowerCase
    @Parsed
    private String firstName;

    @Parsed
    private String lastName;

    @NullString(nulls = { "?", "-" }) // if the value parsed in the quantity column is "?" or "-", it will be replaced by null.
    @Parsed(defaultNullRead = "0") // if a value resolves to null, it will be converted to the String "0".
    private Integer salary; // The attribute name will be matched against the column header in the file automatically.
    ...

}

要解析:

BeanListProcessor<Employee> rowProcessor = new BeanListProcessor<Employee>(Employee.class);

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);

CsvParser parser = new CsvParser(parserSettings);

//And parse!
//this submits all rows parsed from the input to the BeanListProcessor
parser.parse(new FileReader(new File("/path/to/your.csv"))); 

List<Employee> beans = rowProcessor.getBeans();

披露:我是这个图书馆的作者.它是开源且免费的(Apache V2.0许可证).

Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

这篇关于如何在Java中将csv文件映射到pojo类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆