2

I have a bean Person who has a List of "memberOf". Now what I want is, to write one row of this bean per entry of "memberOf" (the project requires it). All my code is written into around beans but I have this issue. Eg:

public class Person {
    @Parsed(field = "USR_USERID")
    private String uid;
    @Parsed(field = "USR_NSUNIQUEID")
    private String nsUniqueID;

    @Parsed(field = "GROUP_NAME")
    List<String>isMemberOf;
    //-- Getters and Setters...
}

Using the CsvWriterSettings and the BeanWriterProcessor what I get in the csv is something like:

"uid","nsuniqueId","[memberOf1, memberOf2...]"

But what I would like is:

"uid","nsuniqueId","memberOf1"
"uid","nsuniqueId","memberOf2"

Is there any way to do that while using the BeanWriterProcessor?

Thanks

Mohit Tyagi
  • 2,788
  • 4
  • 17
  • 29
snap98
  • 23
  • 3

1 Answers1

0

Author of the library here. While the library doesn't support what you want to do it's relatively easy to make it work - the following example is a bit shitty, but will do what you want.

Basically, you can annotate methods of your class. Use that to create a method that returns an element of your isMemberOf every time it is called. For example:

    private int groupNameIndex = 0;

    @Parsed(field = "GROUP_NAME")
    public String nextGroupName() {
        if (hasMoreGroups()) {
            return isMemberOf.get(groupNameIndex++);
        }
        return null;
    }

    public boolean hasMoreGroups() {
        return isMemberOf != null && groupNameIndex < isMemberOf.size();
    }

Then you can write the same bean over and over until hasMoreGroups returns false:

    while (person.hasMoreGroups()) {
        writer.processRecord(person);
    }

Code I used to test:

public static void main(String... args) {
    Person person = new Person();
    person.uid = "XYZ";
    person.nsUniqueID = "abc";
    person.isMemberOf.add("group1");
    person.isMemberOf.add("group2");
    person.isMemberOf.add("group3");

    StringWriter out = new StringWriter();

    CsvWriterSettings settings = new CsvWriterSettings();
    settings.setHeaderWritingEnabled(true);
    settings.setRowWriterProcessor(new BeanWriterProcessor<Person>(Person.class));

    CsvWriter writer = new CsvWriter(out, settings);

    while (person.hasMoreGroups()) {
        writer.processRecord(person);
    }
    writer.close();

    System.out.println(out.toString());
}

Output:

USR_USERID,USR_NSUNIQUEID,GROUP_NAME
XYZ,abc,group1
XYZ,abc,group2
XYZ,abc,group3

Hope it helps

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29