1

I have a List<Person> that I want to write to a CSV-file and then read it again. My problem is that the Person-class have a List<Insurance>-attribute. Therefor the line length will depend on how many objects are in the List<Insurance>-attribute. A Person can have 0 or multiple insurances and these are stored in a List in the specific Person. Is there a reasonable way of doing this?

Like this:

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

I have failed to find questions like mine, but if there are please redirect me. Thanks.

3
  • 1
    I would recommend you to either use json or xml. Commented Apr 10, 2019 at 10:15
  • Consider using another file format for this. Otherwise, consider setting the insurances field to a string delimited by another delimiter (or quoted properly). Commented Apr 10, 2019 at 10:15
  • What kind of format you want your .csv to have? Could you provide an example in your question? Commented Apr 10, 2019 at 10:19

1 Answer 1

1

CSV is not the best choice here because it is supposed to have fixed number of columns for effective parsing. You should use json or xml.

However, if you still want to use CSV, you must ensure there is only 1 list element in the class (future modifications will break the consistency), and that too is written at the end of row.

something like this

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

In your code, only consider first 3 elements as fixed, and iterate over remaining accordingly.

Here is a reference to a problem similar to yours: Using CsvBeanReader to read a CSV file with a variable number of columns

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.