OpenCSV将CSV转换为嵌套Bean [英] OpenCSV convert csv to nested bean

查看:488
本文介绍了OpenCSV将CSV转换为嵌套Bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用OpenCSV. csv为

We are using OpenCSV. The csv is as

id,fname,lname,address.line1,address.line2

豆是

Person{
  String id;
  String lname;
  String fname;
  Address address;
}

Address{
  String line1;
  String line2;  
}

是否可以用opencsv填充嵌套的Address对象! opencsv.beanopencsv.bean.customconverter具有一些类,这些类似乎可以满足我的要求,但找不到任何示例.

Is it possible to fill the nested Address object with opencsv ! The opencsv.bean and opencsv.bean.customconverter have some classes which seems can do what I want but I could not find any samples.

我看过 使用OpenCSV将CSV解析为多种/嵌套的bean类型吗?但答案集中在SuperCSV上,这不是我想要的.

I have seen the Parse CSV to multiple/nested bean types with OpenCSV? but the answer focus on SuperCSV, which is not what I am looking for.

推荐答案

一种选择是创建自定义

One option is to create a custom MappingStrategy class and implement the method populateNewBean(...) providing you means to populate beans as you like.

请参见以下示例:

public void example() {
    Reader in = new StringReader(
            "1,Doe,John,123 Main St,\"Anytown, USA\"\n" +
            "2,Dean,James,111 Some St,\"Othertown, USA\"\n" +
            "3,Burger,Sam,99 Beach Avenue,\"Sometown, USA\"\n");
    CsvToBeanBuilder<Person> builder = new CsvToBeanBuilder<Person>(in)
            .withMappingStrategy(new PersonMappingStrategy());
    CsvToBean<Person> ctb = builder.build();
    for (Person person : ctb.parse()) {
        System.out.println(
                person.id
                + "\t" + person.lname
                + "\t" + person.fname
                + "\t" + person.address.line1
                + "\t" + person.address.line2);
    }
}

class Person {
    String id;
    String lname;
    String fname;
    Address address;
}

class Address {
    String line1;
    String line2;  
}

class PersonMappingStrategy extends ColumnPositionMappingStrategy {

    public PersonMappingStrategy() {
        this.setType(Person.class);
    }

    @Override
    public Object populateNewBean(String[] line) throws CsvBeanIntrospectionException, CsvRequiredFieldEmptyException,
    CsvDataTypeMismatchException, CsvConstraintViolationException, CsvValidationException {
        Person person = new Person();
        person.id = line[0];
        person.lname = line[1];
        person.fname = line[2];
        person.address = new Address();
        person.address.line1 = line[3];
        person.address.line2 = line[4];
        return person;
    }

}

输出为

1       Doe     John    123 Main St     Anytown, USA
2       Dean    James   111 Some St     Othertown, USA
3       Burger  Sam     99 Beach Avenue Sometown, USA

这篇关于OpenCSV将CSV转换为嵌套Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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