How to Write Complex Java Object to CSV File

Pr0pagate :

So, I know how to write a simple Java object to a CSV file, but I am having trouble with a Java object that has more complex attributes. Below is an example of what I currently have:

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();
    }
}

This works as far as creating a valid CSV file (for the most part), but the CSV file does not contain any of the AddressInfo attributes. The inverse of this (reading from CSV to Java Object) works just fine, so I'm not entirely sure what I'm doing wrong. Does anyone have any experience on the matter or know what I might need to correct here?

Jeronimo Backes :

This is supported in univocity-parsers. Just use the @Nested annotation and everything will be mapped properly:

public class Person {

    @Parsed
    private String name;

    @Parsed
    private String position;

    @Nested
    private AddressInfo info;

}

To write such structure to a CSV:

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

Hope this helps.

Disclaimer: I'm the author of this library (Apache 2.0 license)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=156755&siteId=1