super-csv嵌套bean

dxpyg8gm  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(289)

我有一个csv

id,name,description,price,date,name,address
1,SuperCsv,Write csv file,1234.56,28/03/2016,amar,jp nagar

我想读取它并将其存储到json文件中。我已经创建了两个bean课程(id,name,description,price,date)和person(name,address)
通过bean阅读器阅读时,我无法设置个人地址。(美化的)输出是

Course [id=1,
        name=SuperCsv,
        description=Write csv file,
        price=1234.56,
        date=Mon Mar 28 00:00:00 IST 2016,
        person=[
            Person [name=amar, address=null],
            Person [name=null, address=jpnagar]
        ]
]

我想把地址改成名字
我的代码:

public static void readCsv(String csvFileName) throws IOException {

        ICsvBeanReader beanReader = null;
        try {
            beanReader = new CsvBeanReader(new FileReader(csvFileName), 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();

            final String[] fieldMapping = new String[header.length];

            for (int i = 0; i < header.length; i++) {
                if (i < 5) {
                    // normal mappings
                    fieldMapping[i] = header[i];

                } else {
                    // attribute mappings
                    fieldMapping[i] = "addAttribute";

                }}
            ObjectMapper mapper=new ObjectMapper();
            Course course;
            List<Course> courseList=new ArrayList<Course>();
            while ((course = beanReader.read(Course.class, fieldMapping, processors)) != null) {
                // process course
                System.out.println(course);
                courseList.add(course);

            }
private static CellProcessor[] getProcessors(){

        final CellProcessor parsePerson = new CellProcessorAdaptor() {
            public Object execute(Object value, CsvContext context) {
                return new Person((String) value,null);
            }
        };  

        final CellProcessor parsePersonAddress = new CellProcessorAdaptor() {
            public Object execute(Object value, CsvContext context) {
                return new Person(null,(String) value);
            }
        };

        return new CellProcessor[] {
                new ParseInt(),
                new NotNull(),
                new Optional(),
                new ParseDouble(),
                new ParseDate("dd/MM/yyyy"),
                new Optional(parsePerson),
                new Optional(parsePersonAddress)        
        };
rks48beu

rks48beu1#

supercsv是我见过的第一个允许在对象中创建对象的解析器。
对于您想要的内容,您可以尝试使用apachecommons csv或opencsv(csvtobean)进行Map,但要做到这一点,您需要在外部类中设置内部类(setname,setaddress)的setter,以便csvtobean能够获取它。这可能有用,也可能无效。
我通常告诉人们的是一个普通的pojo,它包含csv中的所有字段-一个数据传输对象。让解析器创建,然后使用实用程序/生成器类将普通pojo转换为所需的嵌套pojo。

相关问题