Search code examples
univocity

Univocity - Parse single row into multiple beans


Is it possible to parse a single line into multiple beans based on index ranges

Example:

Line: "field1", "field2", "field3", ...., "field9"

class ColumnsOneAndTwo {
   protected String field1;
   protected String field2;
}

class ColumnThreeAndNine {
   protected String field3;
   protected String field9;
}

class Row {

  @Parsed(indexes = 0, 1)
  protected ColumnOneAndTwo fields;

  @Parsed(indexes = 2, 8)
  protected ColumnThreeAndNine moreFields;

} 

BeanListProcessor<Row> rowProcessor = new BeanListProcessor<Row>(Row.class);

CsvRoutines routines = new CsvRoutines(parserSettings);

for (Row data : routines.iterate(Row.class, <file>, "UTF-8")) {  

}

Solution

  • You are looking for the @Nested annotation. Just use:

    class ColumnsOneAndTwo {
        @Parsed(index=1)
        protected String field1;
    
        @Parsed(index=2)
        protected String field2;
    }
    
    class ColumnThreeAndNine {
        @Parsed(index=3)
        protected String field3;
    
        @Parsed(index=9)
        protected String field9;
    }
    
    class Row {
    
       @Nested
       protected ColumnOneAndTwo fields;
    
       @Nested
       protected ColumnThreeAndNine moreFields;
    
    } 
    

    Hope it helps.

    Disclaimer: I'm the author of this library. It's open source and free (Apache 2.0 license)