Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get header of csv using jackson-dataformat-csv

Tags:

java

csv

jackson

I using jackson-dataformat-csv library. I want parse CSV file. I have this code:

 CsvMapper csvMapper = new CsvMapper();
        CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();
        List<Map<String, String>> csvRows;
        try {
            MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class)
                    .with(csvSchema.withColumnSeparator(';'))
                    .readValues(file.getInputStream());
            csvRows = it.readAll();
        } catch (Exception ex) {
            log.error("Unable to read csv document: ", ex);
        }

I want get column names from this file. But I don't understand how to make it. I try:

csvSchema._columns

But, It is empty object. Too I make this:

csvSchema.column(0)

I get error:

Method threw 'java.lang.ArrayIndexOutOfBoundsException' exception.

Obviously, columns object is empty. Why? How I get array of column names from CSV?

like image 216
All_Safe Avatar asked Jan 01 '23 04:01

All_Safe


2 Answers

the fields are not in CsvSchema until you get the Parser from MappingIterator

a working example:

CsvSchema schema = (CsvSchema) objectMappingIterator.getParser().getSchema();
        Iterator<CsvSchema.Column> iterator = schema.iterator();
        while (iterator.hasNext()) {
            CsvSchema.Column next = iterator.next();
            next.getName();
        }
like image 148
HungUnicorn Avatar answered Jan 13 '23 13:01

HungUnicorn


If you need column names you have them as keys in Map returned by MappingIterator:

CsvMapper csvMapper = new CsvMapper();
CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();

MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class)
        .with(csvSchema.withColumnSeparator(','))
        .readValues(csvFile);

System.out.println("Column names: " + it.next().keySet());
like image 43
Michał Ziober Avatar answered Jan 13 '23 12:01

Michał Ziober