Univocity CSV parser multiple beans with multiple rows in single CSV

大憨熊 提交于 2020-01-05 08:32:34

问题


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.



来源:https://stackoverflow.com/questions/51882254/univocity-csv-parser-multiple-beans-with-multiple-rows-in-single-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!