本文介绍了Univocity CSV解析器在单个CSV中具有多个行的多个bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下课程

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

和以下CSV(使用','作为分隔符,但为了便于查看,我在此处使用了空格):

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

在这种情况下,"IH"表示此行是库存标头,而"IL"表示它是库存行.库存标题后的库存行仅与该库存有关.库存对象的末尾用新的库存标题行或文件的末尾表示.

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.

我想将其解析为一个列表.解析单个Inventory对象非常简单,只需在第0列上添加ValueSwitch,为InventoryHeader和InventoryLine创建BeanListProcessor,然后将结果添加到新的Inventory对象中即可.

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?

推荐答案

此处的库作者.检查此示例,因为它看起来与您的案例非常相似.

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

您需要重写InputValueSwitchrowProcessorSwitched方法,以了解解析器何时开始处理其他行格式.

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

类似这样的东西:

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
    }
}

希望这会有所帮助.

这篇关于Univocity CSV解析器在单个CSV中具有多个行的多个bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 14:45