csv to pojo with another pojo

徘徊边缘 提交于 2020-01-15 11:06:13

问题


Orgnization{

private String name;
private String uniqueId;
private boolean selfRegEnabled;
private List<Address> addrList;

public void setAddress(Address a){..}
public void setName(String name){..}

}

Addess{
private String type;
private String line1;
private String line2;
private String line3;
private String city;
private String state;
private String zip;
private String country;
}

CSV Header Columns are as below

System.UniqueID,Name,EnableSelf-Registration,Addr1.Type,Addr1.Line1,Addr1.Line2,Addr1.Line3,Addr1.City,Addr1.State,Addr1.Zip,Addr1.Country,Addr2.Type,Addr2.Line1,Addr2.Line2,Addr2.Line3,Addr2.City,Addr2.State,Addr2.Zip,Addr2.Country,Addr3.Type,Addr3.Line1,Addr3.Line2,Addr3.Line3,Addr3.City,Addr3.State,Addr3.Zip,Addr3.Country

My question might be related to below link

OpenCSV CSV to JavaBean

I didn't see that thread has a proper answer (I am not sure if I miss any from that thread)

Can we achieve same thing with any of the existing csv libraries such as supercsv, opencsv?

If I am using supercsv - can I map System.UniqueID column of csv to systemUniqueID property of my bean


回答1:


You can certainly do this with Super CSV using CsvDozerBeanReader. See this example on the website.

It's also explained in a bit more detail on this SO answer.

You may also be interested in this recent question, as it demonstrates the different ways to achieve deep/indexed mapping with Super CSV (with and without using Dozer).

Following the CsvDozerBeanReader example on the website, to read the CSV from your question you would use a field mapping of:

final String[] fieldMapping = new String[]{
    "uniqueId",
    "name",
    "selfRegEnabled",
    "addrList[0].type",
    "addrList[0].line1",
    "addrList[0].line2",
    "addrList[0].line3",
    "addrList[0].city",
    "addrList[0].state",
    "addrList[0].zip",
    "addrList[0].country",
    "addrList[1].type",
    "addrList[1].line1",
    "addrList[1].line2",
    "addrList[1].line3",
    "addrList[1].city",
    "addrList[1].state",
    "addrList[1].zip",
    "addrList[1].country",
    "addrList[2].type",
    "addrList[2].line1",
    "addrList[2].line2",
    "addrList[2].line3",
    "addrList[2].city",
    "addrList[2].state",
    "addrList[2].zip",
    "addrList[2].country"
};

Also, because the selfRegEnabled field is a boolean, you'll need to use cell processors to transform the String value into a Boolean - to do this you'd use the ParseBool processor.



来源:https://stackoverflow.com/questions/16363092/csv-to-pojo-with-another-pojo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!