如何将复杂的Java对象写入CSV文件

时间:2019-05-20 19:15:09

标签: java file csv nested opencsv

因此,我知道如何将简单的Java对象写入CSV文件,但是我遇到了具有更复杂属性的Java对象的麻烦。以下是我目前拥有的示例:

Person.java

public class Person {
    @CsvBindByName(column="name")
    private String name;

    @CsvBindByName(column="position")
    private String position;

    private AddressInfo info;

    // getters and setters ...

    // overridden toString method ...
}

AddressInfo.java

public class AddressInfo {
    @CsvBindByName(column="street")
    private String street;

    @CsvBindByName(column="city")
    private String city;

    @CsvBindByName(column="state")
    private String state;

    // getters and setters ...

    // overridden toString method ...
}

PersonWriter.java

public class PersonWriter {
    private static final Logger LOGGER = LoggerFactory.getLogger(PersonWriter.class);

    public static boolean writeCsVFromPerson(String directory, List<Person> persons) {
        File file = new File(directory + "/person-" + System.nanoTime() + ".csv");
        try {
            Writer writer = new FileWriter(file);
            MappingStrategy<Person> ms = new HeaderColumnNameMappingStrategy<Person>();
            ms.setType(Person.class);
            StatefulBeanToCsv<Person> sbc = new StatefulBeanToCsvBuilder<Person>(writer)
                    .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
                    .withMappingStrategy(ms)
                    .build();
            sbc.write(persons);
            writer.close();
        } catch (Exception e) {
            LOGGER.error("Failed to create Person CSV file", e)            
        }
        return file.exists() && file.isFile();
    }
}

(在大多数情况下)这可以创建有效的CSV文件,但是CSV文件不包含任何AddressInfo属性。反之(从CSV读取到Java Object)效果很好,所以我不确定自己在做什么错。是否有人对此事有经验或知道我可能需要在这里纠正的问题?

1 个答案:

答案 0 :(得分:1)

univocity-parsers支持此功能。只需使用@Nested批注,所有内容都将正确映射:

public class Person {

    @Parsed
    private String name;

    @Parsed
    private String position;

    @Nested
    private AddressInfo info;

}

要将此类结构写入CSV:

List<Person> persons = buildYourPersonList();
File file = new File(directory + "/person-" + System.nanoTime() + ".csv");
new CsvRoutines(settings).writeAll(persons, Person.class, file, "UTF-8");

希望这会有所帮助。

免责声明:我是该库的作者(Apache 2.0许可证)