Search code examples
javacsvunivocity

Write Object with Collection to CSV using UniVocity


Given two Classes

public class Inventory {
    private List<InventoryLine> lines;
}

and

public class InventoryLine {
    private String itemName;
    private int quantity;
    private String description;
}

I would like to print the following CSV file (using ',' as the delimiter but for visibility's sake I used spaces here):

Name    Quantity    Description
Book    4           A book
Watch   0           Gold watch
Phone   8           iPhone 8

Using the Conversion annotation and a class implementing the Conversion interface provided would it be possible to create the above CSV (by printing the Inventory class)? I see that they have provided examples with a List but they merge them into one column using a delimiter. I don't see any examples with this case.


Solution

  • Author of the library here. The parser doesn't handle a hierarchical structure of classes. You can only write the list itself:

    new CsvRoutines().writeAll(inventory.getLines(), InventoryLine.class, new File("/path/to/your.csv"), "UTF-8");
    

    Hope this helps.