Theiaz
Theiaz

Reputation: 784

Write single bean rowise per attribute to csv

I'm using opencsv and I've got a single model (lets say Person with three attributes name, age, sex) which I want to store to a csv-file.

It should look like the following:

"name";"Jon";
"age";"30";
"sex";"male";

The first column contains the property name and the second one contains the value (like a key-value pair).

My implementation looks like the following:

writer = new FileWriter("./settings.csv");

StatefulBeanToCsvBuilder<Person> beanToCsv = new StatefulBeanToCsvBuilder<SettingsModel>(writer);
StatefulBeanToCsv<SettingsModel> beanWriter = beanToCsv.build();
beanWriter.write(model);
writer.close();

I know that there are some settings available with on beanToCsv but I've got no clue how.

If its even possible? Thanks for your help :)

Upvotes: 1

Views: 529

Answers (1)

Lau Ka Fai
Lau Ka Fai

Reputation: 174

StatefulBeanToCsv has a standard manner to serialize bean into tabular format.

What you really want is to flatten the bean into Key-Value pair. So the trick should use a BeanMap to hold Person bean data. As Person bean has no nested object, we can simply transform it into ValueHolder.key and ValueHolder.value.

Eventually apply this strategy ColumnPositionMappingStrategy in this way:

ColumnPositionMappingStrategy<ValueHolder> strategy = new ColumnPositionMappingStrategy<>();
strategy.setType(ValueHolder.class);
strategy.setColumnMapping("key", "value");
FileWriter writer = new FileWriter("./settings.csv");
StatefulBeanToCsvBuilder<ValueHolder> csvBuilder = new StatefulBeanToCsvBuilder<>(writer);
StatefulBeanToCsv<ValueHolder> beanWriter = csvBuilder.withSeparator(';').withMappingStrategy(strategy).build();
beanWriter.write(content);
writer.close();

Full working sample can be accessed here.

Upvotes: 4

Related Questions