How to map nested beans to csv using OpenCSV?
Brought to you by:
aruckerjones,
sconway
I am taking data from database and populating it in my POJOs and then using Opencsv to generate a csv file with | delimiter,My Pojo's looks like:
class POJO1{
field a;
field b;
list<class POJO2>;
list<class POJO3>;
}
class POJO2{
field c;
field d;
field e;
field f;
}
class POJO3{
field g;
field h;
field i;
field j;
}
and the file generated by it will be like:
a|b
c|d|e|f
g|h|i|j
But this is not a CSV file. In a CSV file, the values in any given column all have the same meaning. Here you have a variable number of columns, and the data fields in each record don't seem to be related to the corresponding data fields in the last record.
I found similar post on Stackoverflow for reading and i was expecting for both reading and Writing:
https://stackoverflow.com/questions/65493456/can-opencsv-be-used-to-parse-multiline-records
I am trying to parse a file similar to this using OpenCSV -
CUST,Warren,Q,Darrow,8272 4th Street,New York,IL,76091
TRANS,1165965,2011-01-22 00:13:29,51.43
CUST,Erica,I,Jobs,8875 Farnam Street,Aurora,IL,36314
TRANS,8116369,2011-01-21 20:40:52,-14.83
TRANS,8116369,2011-01-21 15:50:17,-45.45
TRANS,8116369,2011-01-21 16:52:46,-74.6
TRANS,8116369,2011-01-22 13:51:05,48.55
TRANS,8116369,2011-01-21 16:51:59,98.53
I will use Customer object to read the records starting with 'CUST'. The Customer object will contain a List of transactions.
public class Customer {
private String firstName;
private String middleInitial;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
List<transaction> transactions;
...
}
I will use Transaction object to read the records starting with 'TRANS'.</transaction>
public class Transaction {
private String accountNumber;
private Date transactionDate;
private Double amount;
...
}
One Customer can have one or more Transaction. Is there any way to achieve this functionality?
Again: no. This is not a CSV file, even though the fields are separated by commas. In a CSV file, every record is independent of the previous records.
Recursion is possible with the CsvRecurse annotation, but that does not work with lists or anything else variable-length.
Everything for one outer bean class would have to be in one record, including all of the nested inner beans. That would leave you with the problem of parsing each inner record in the list as a CSV. In other words, you would have CSV within CSV. We don't do that, either.
All of that said, you can always ressort to using the lowest-level parsing of individual lines and filling the bean fields yourself. You wouldn't be using the bean functionality of opencsv, but you would at least make use of the parsing code.
Thanks for your quick responses.