Univocity CSV parser multiple beans with multiple

2019-07-25 16:50发布

问题:

Given the following classes

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

public class InventoryHeader {
    private String date;
    private boolean isCurrent;
}


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

and the following CSV (using ',' as the delimiter but for visibility's sake I used spaces here):

IH    2007-06-05    false
IL    Watch         7
IL    Flower Pot    9
IL    Chicken Wing  29
IH    2010-07-30    true
IL    Cable         200
IL    Fish Tank     87

In this case 'IH' denotes this line being an inventory header and 'IL' denotes it being an inventory line. The inventory line rows following an inventory header pertain to that inventory only. The end of an Inventory object is denoted either by a new inventory header row, or the end of a file.

I would like to parse this into a List. Parsing a single Inventory object is simple, just add a ValueSwitch on column 0, create a BeanListProcessor for InventoryHeader and InventoryLine and just add the results to a new Inventory object.

With the above method, we would get a list of headers and lines but how would it be possible to know which lines correspond to which headers?

回答1:

Author of the library here. Check this example as it seems very similar to your case.

You need to override the rowProcessorSwitched method of your InputValueSwitch to know when the parser starts processing a different row format.

Something like this:

public void rowProcessorSwitched(RowProcessor from, RowProcessor to) {
    if(from == inventoryLineProcessor){ // stopped processing inventory lines and will process some other row.
        List<InventoryLine> inventoryLines = inventoryLineProcessor.getBeans();

        //now assign a copy of this list to the last InventoryHeader you have
    }
}

Hope this helps.