Jackson CsvMapper : parse CSV into objects by dynamic column names

97 Views Asked by At

I'd like to parse CSV using headers as a value of ouput object

CSV looks like:

header_1,header_2,header_3,header...
v1_1,v1_2,v1_3,v1_...
v2_1,v2_2,v2_3,v2_...
...

using that I want values with headers to go a list of list of objects like

record Obj(String name, String value) {}

the only thing I get to do is the example in the CsvMapper documentation https://cowtowncoder.medium.com/reading-csv-with-jackson-c4e74a15ddc1#ab6e

here the readAll returns a List<Map<String, String>>

MappingIterator<Map<String, String>> it = mapper
                .readerForMapOf(String.class)
                .with(schema)
                .readValues(<csv_example_above>);
... it.readAll();
... equals ...
List.of(
Map.of("header_1","v1_1","header_2","v1_2","header_3","v1_3"), // line 1
Map.of("header_1","v2_1","header_2","v2_2","header_3","v2_3"), // line 2
...
);

but what I want is List<List<Obj>>:

List.of(
    List.of(new Obj("header_1","v1_1"), new Obj("header_2","v1_2"), new Obj("header_3","v1_3"), ...), // line 1
    List.of(new Obj("header_1","v2_1"), new Obj("header_2","v2_2"), new Obj("header_3","v2_3"), ...), // line 2
...);

I'm just wondering on how to get this quickly with deserialization (if it's possible) :/

NB : I don't know the length of the header line nor of the line numbers

0

There are 0 best solutions below