4

I have to write nested list of objects(StoreLocations) into Csv file using open csv. My model classes are-

public class StoreLocation {
    private String name;
    private String city;
    private int zip;
    private String streetAndNumber;
    private List<String> keywords;
    private Double lat;
    private Double lng;
    private List<OpeningHours> openingHours;
}

public class OpeningHours {
    private String dayOfWeek;
    private String from1;
    private String to1;
}

My method to write-

public void getStoreLocationData(List<StoreLocation> storeLocations) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
        try (
                Writer writer = Files.newBufferedWriter(Paths.get(storeLocationDataCsv))
        ) {
            StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .build();
            beanToCsv.write(storeLocations);
        }
    }

This code generates all columns perfectly, except the list of opening hours. This is the current output-enter image description here I would prefer to either have a column of opening hours and arrange each opening hour as a new row. Something likeenter image description here or having all opening hours in a json list inside opening hours column. Probably I need columnPositionMappingStrategy to set these columns, but I need clue how to use it?

Here is the json representation of the List of array locations-

[{
"name":"OBI Markt Kempen",
"city":"Kempen",
"zip":47906,
"streetAndNumber":"Kleinbahnstraße 32",
"keywords":[],
"lat":51.3740233,
"lng":6.4182039,
"openingHours":
[{"dayOfWeek":"1","from1":"08:00","to1":"20:00"},
{"dayOfWeek":"2","from1":"08:00","to1":"20:00"},
]}]

Note: I tried using super csv () referring to Parse CSV to multiple/nested bean types with OpenCSV? ,bur it makes pretty complicated and also I don't understand how to write it to the file.

Also I have referred all the articles for writing complex/nested java object to csv over stackoverflow.

Caffeine Coder
  • 344
  • 1
  • 11

0 Answers0