Java to CSV file, SuperCSV Dozer: How to avoid looping for a nested object

人走茶凉 提交于 2019-12-02 10:50:50

The answers field in SurveyResponse is a List, so you have to use indexed mapping to configure CsvDozerBeanWriter. Indexed mapping is not actually looping - it's just how Dozer knows which element of a List to populate. This is extremely important if you were to ignore a column - it would actually insert a null element for that column.

If you don't use indexed mapping (and just use "answers") then you'd need to configure a cell processor that can take a List<Answer> and convert it to something that can be used as CSV.

Dynamically configuring the field mapping

(Not what you were asking as it turns out, but I'll leave for future reference)

That doesn't mean you have to configure the field mapping with a static String array. You can populate the array dynamically using a simple for-loop. For example,

    String[] fieldMapping = new String[10];
    fieldMapping[0] = "age";
    fieldMapping[1] = "consentGiven";
    int answerStartIndex = 2;
    int answerEndIndex = 8;
    for (int i = answerStartIndex; i <= answerEndIndex; i++){
        fieldMapping[i] = String.format("answers[%s].questionNo", 
            i - answerStartIndex);
    }
    fieldMapping[9] = "age";

Which will give you a fieldMapping of:

[age, consentGiven, answers[0].questionNo, answers[1].questionNo,
 answers[2].questionNo, answers[3].questionNo, answers[4].questionNo,
 answers[5].questionNo, answers[6].questionNo, age]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!