Univocity CSV 解析器在单个 CSV 中具有多行的多个 bean
Univocity CSV parser multiple beans with multiple rows in single CSV
给出以下 类
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(使用“,”作为分隔符,但为了可见性,我在这里使用了空格):
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' 表示此行是库存行 header,'IL' 表示它是库存行。库存 header 之后的库存行仅与该库存有关。清单 object 的末尾由新清单 header 行或文件末尾表示。
我想将其解析为一个列表。解析单个 Inventory object 很简单,只需在第 0 列添加一个 ValueSwitch,为 InventoryHeader 和 InventoryLine 创建一个 BeanListProcessor,然后将结果添加到一个新的 Inventory object.
用上面的方法,我们会得到一个headers和行的列表,但是怎么可能知道哪些行对应于哪些headers呢?
这里是图书馆的作者。检查 this example,因为它看起来与您的情况非常相似。
您需要覆盖 InputValueSwitch
的 rowProcessorSwitched
方法以了解解析器何时开始处理不同的行格式。
像这样:
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
}
}
希望对您有所帮助。
给出以下 类
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(使用“,”作为分隔符,但为了可见性,我在这里使用了空格):
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' 表示此行是库存行 header,'IL' 表示它是库存行。库存 header 之后的库存行仅与该库存有关。清单 object 的末尾由新清单 header 行或文件末尾表示。
我想将其解析为一个列表。解析单个 Inventory object 很简单,只需在第 0 列添加一个 ValueSwitch,为 InventoryHeader 和 InventoryLine 创建一个 BeanListProcessor,然后将结果添加到一个新的 Inventory object.
用上面的方法,我们会得到一个headers和行的列表,但是怎么可能知道哪些行对应于哪些headers呢?
这里是图书馆的作者。检查 this example,因为它看起来与您的情况非常相似。
您需要覆盖 InputValueSwitch
的 rowProcessorSwitched
方法以了解解析器何时开始处理不同的行格式。
像这样:
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
}
}
希望对您有所帮助。