【问题标题】:Writing and reading Java objects to CSV that have Lists as attributes将 Java 对象写入和读取以列表为属性的 CSV
【发布时间】:2019-08-31 18:15:57
【问题描述】:

我有一个List<Person>,我想将其写入 CSV 文件,然后再次读取。我的问题是Person-class 有一个List<Insurance>-attribute。因此,行长将取决于List<Insurance>-属性中有多少对象。 Person 可以有 0 个或多个保险,这些保险存储在特定的 Person 中的 List 中。有没有合理的方法来做到这一点?

像这样:

public class Person {
    private int insuranceNR;
    private String firstName;
    private String lastName;
    private List<Insurance> insurances;
}

我没有找到像我这样的问题,但如果有请重定向我。谢谢。

【问题讨论】:

  • 我建议您使用jsonxml
  • 考虑为此使用另一种文件格式。否则,请考虑将insurances 字段设置为由另一个分隔符分隔的字符串(或正确引用)。
  • 您希望您的 .csv 文件采用哪种格式?你能在你的问题中提供一个例子吗?

标签: java list csv


【解决方案1】:

CSV 不是这里的最佳选择,因为它应该具有固定数量的列以进行有效解析。您应该使用 json 或 xml。

但是,如果您仍想使用 CSV,则必须确保类中只有 1 个列表元素(将来的修改会破坏一致性),并且也写在行尾。

类似的东西

1, Bill, Gates, Ins1, Ins2, Ins3 
2, Donald, Trump 
3, Elon, Musk, Ins4 
4, Jeff, Bezos, Ins5, Ins6, Ins7, Ins8, Ins9

在您的代码中,仅将前 3 个元素视为固定的,并相应地迭代剩余的元素。

这里引用了一个与您类似的问题: Using CsvBeanReader to read a CSV file with a variable number of columns

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多