0

How can I read a csv file which has duplicate column names by using BeanParser.

Below is the example header

Col desc, Col amount, Col desc, Col amount

test, 12.44, test2, 43.44

1 Answers1

0

You can set the header names manually:

public class MyClass {

    @Parsed(field = "amount1")
    private BigDecimal amount1;

    @Parsed(field = "amount2")
    private BigDecimal amount2;

    @Parsed(field = "description1")
    private String description1;

    @Parsed(field = "description2")
    private BigDecimal description2;
}

Then:

CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.setHeaderExtractionEnabled(true); //to read your input headers with duplicates.
parserSettings.setHeaders("description1", "amount1, "description2", "amount2"); //to override the headers in the input with the names you want to work with

Then parse:

List<MyClass> myList = new CsvRoutines(parserSettings).parseAll(MyClass.class, <input>);

You can also use the field index instead of the field names in the annotations, so you don't need to worry about header names.

Hope this helps

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29
  • Thanks for the quick response. – raman jillella Jul 27 '17 at 09:56
  • No problem, if it helped to solve your problem please upvote / mark the answer as accepted. Best regards – Jeronimo Backes Jul 27 '17 at 10:14
  • Thanks for the quick response. Here I am adding little bit complexity to the question. The above mentioned columns are not just 4. They are 32, 16 descriptions 16 amounts along with the some other 100 columns. I am thinking to prepare the bean by using BeanParser for 100 columns and populate the other properties manually by getting them from context. is there any other way to do this. – raman jillella Jul 27 '17 at 10:30
  • Not sure what you need to do with the data but it might be easier to not even use a bean, but parse by record. Use `parser.parseNextRecord()` or `parser.parselAllRecords()` then get the values like this: `Map data = record.toFieldMap()` – Jeronimo Backes Jul 27 '17 at 10:53
  • The problem with the above approach is, if the column names are same they are overriding the values because it is a map. – raman jillella Jul 27 '17 at 12:58
  • use `record.toIndexMap` – Jeronimo Backes Jul 27 '17 at 12:59
  • or set the header list manually with `parserSettings.setHeaders(""description1", "amount1, "description2", "amount2"...)` – Jeronimo Backes Jul 27 '17 at 13:00
  • Thanks Jeronimo Backes. When I set headers manually parser is reading only one row from the file. Same code with out setHeaders(""...) was able to read all the rows. What could be the reason? can you please guide me. – raman jillella Aug 17 '17 at 09:46