Opencsv、StatefulBeanToCsv 将嵌套的对象列表写入 csv

问题描述 投票:0回答:1

我必须使用打开的 csv 将嵌套的对象列表(StoreLocations)写入 Csv 文件。 我的模型类是-

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;
}

我的写作方法-

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);
        }
    }

此代码完美生成除营业时间列表之外的所有列。 这是当前的输出- 我希望要么有一列开放时间,并将每个开放时间安排为新行。 类似的东西 或者将所有开放时间放在开放时间列内的 json 列表中。 也许我需要 columnPositionMappingStrategy 来设置这些列,但我需要知道如何使用它?

这是数组位置列表的 json 表示形式 -

[{
"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"},
]}]

注意:我尝试使用 super csv () 指的是 使用 OpenCSV 将 CSV 解析为多个/嵌套 bean 类型?,但是它变得非常复杂,而且我也不明白如何将其写入文件。

我还参考了所有关于通过 stackoverflow 将复杂/嵌套 java 对象写入 csv 的文章。

java list csv opencsv writetofile
1个回答
0
投票
public class CustomMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {

    public String[] generateHeader() {
        
            return new String[]{"name","city","zip",
           "streetAndNumber" ,"keywords","lat","lon","openingHrs_dayOfWeek","openingHrs_froml","openingHrs_to1"
          
        };
        
    }
    
    //override transmuteBean  or toString() in StoreLocation
        @Override
    public String[] transmuteBean(T bean) {
        // Override this method to handle nested objects
        if (bean instanceof StoreLocation ) {
            return toStringArray((StoreLocation) bean);
        } else {
            
            return new String[0]; 
        }
    }
    
    
    public String[] toStringArray(StoreLocation storeLocation) {
        return new String[] {
                String.valueOf(storeLocation.getName()),
        
                String.valueOf(storeLocation.getCity()),
                String.valueOf(storeLocation.getZip()),
                String.valueOf(storeLocation.getStreeAndNumber()),
                String.valueOf(storeLocation.getKeyWords().toString()),
                String.valueOf(storeLocation.getLat()),
                String.valueOf(storeLocation.getLon()),
                List<OpeningHours> openingHours = storeLocation.getOpeningHrs();
                for(OpeningHours obj: openingHours)
                { 
                String.valueOf(obj.getDayOfWeek()),
                String.valueOf(obj.getFrom1()),
                String.valueOf(obj.getTo1()),
                }
                
        
        };
    }
    
    }
    
    //use above strategy 
    
    public void getStoreLocationData(List<StoreLocation> storeLocations) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException {
    
      CustomMappingStrategy<StoreLocation> strategy = new CustomMappingStrategy<>();
        String[] headers=strategy.generateHeader();
        strategy.setType(StoreLocation.class);
        strategy.setColumnMapping(headers);
       
        try (
                Writer writer = Files.newBufferedWriter(Paths.get(storeLocationDataCsv))
        ) {
            StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
                    .withMappingStrategy(mappingStrategy)
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .build();
            beanToCsv.write(storeLocations);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.