How to parse TSV data into nested objects

273 views Asked by At

I'm trying to parse the following TSV data into a nested object but my "title" field is always null within the Nested class.

I've included the method at the bottom which converts the TSV data to the object.

value1 | metaData1 | valueA |
value2 | metaData2 | valueB |
value3 | metaData3 | valueC |

public class Data {
    @Parsed(index = 0)
    private String value0;

    @Parsed(index = 1)
    private String foo;

    @Nested
    MetaData metaData;

    public static class MetaData {
        @Parsed(index = 1)
        private String title;
    }
}

public <T> List<T> convertFileToData(File file, Class<T> clazz, boolean removeHeader) {

    BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);
    CsvParserSettings settings = new CsvParserSettings();
    settings.getFormat().setDelimiter('|');
    settings.setProcessor(rowProcessor);
    settings.setHeaderExtractionEnabled(removeHeader);

    CsvParser parser = new CsvParser(settings);
    parser.parseAll(file);

    return rowProcessor.getBeans();
}
1

There are 1 answers

4
Jeronimo Backes On BEST ANSWER

You forgot to define an index on your Metadata.title:

public static class MetaData {
    @Parsed(index=1)
    private String title;
}

Also, you are setting the delimiter to \t while your input is using | as the separator.