I'm trying create a List from especific positions in the csv file, instead parentheses.
class Person {//
@Parsed
private String name;
@??
private Address address;
@Convert(conversionClass = Emails2.class, args = { "," , "5,6" })
@Parsed
private List<String> emails;
}
csv format:
name,email1,email2,email3,street,number,neighborhood
Maria,ma@gmail.com,ma@hotmail.com,,Regent Street,12,downtown
Ana,ana@gmail.com,a@hotmail.com,,Bird Street,,east side
I need read the csv file and create a list of emails and an object of Address. I was trying to use @Convert,
public class Emails2 implements Conversion<String, Set<String>> {
private final String separator;
private final Set<String> positions;
public Emails2(String... args) {
String separator = ",";
Set<String> positions = null;
if (args.length == 1) {
separator = args[0];
}
if (args.length == 2) {
positions = new HashSet<String>();
String[] posi = args[1].split(",");
for (String string : posi) {
positions.add(string);
}
}
this.separator = separator;
this.positions = positions;
}
public Emails2(String separator, Set<String> positions) {
this.separator = separator;
this.positions = positions;
}
//this method is not called, I don't know why
public Set<String> execute(String input) { //I would like add the list and Address object inside this method to get it done in beanProcessed(...)
if (input == null) {
return Collections.emptySet();
}
Set<String> out = new TreeSet<String>();
for (String token : input.split(separator)) {
for (String word : token.trim().split("\\s")) {
out.add(word.trim());
}
}
return out;
}
public String revert(Set<String> input) {
return revert(input);
}
}
How i'm doing
public static void main(String[] args) {
BeanProcessor<Person> rowProcessor = new BeanProcessor<Person>(Person.class) {
@Override
public void beanProcessed(Person c, ParsingContext context) {
System.out.println(c.getName());
String[] positions = context.currentParsedContent().split(",");
System.out.println(positions[5]);
//I'm using fixed position here, I'd like get the position from @Convert or another way by configuration
System.out.println(positions[6]);
List<String> list = new ArrayList<>();
list.add(positions[5]);
list.add(positions[6]);
c.setEmails(list);
}
};
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setRowProcessor(rowProcessor);
parserSettings.setHeaderExtractionEnabled(true);
CsvParser parser2 = new CsvParser(parserSettings);
parser2.parse(getReader("/var/lib/cob/test2.csv"));
}