jackson-dataformat-csv - are custom column names possible?
Asked Answered
P

1

12

Is it possible to define custom header names when serializing a POJO into CSV.

In other words, if I have a field named someField in my PoJO, I would like the header column in output CSV file to be named Some custom field name for example.

Thanks.

Pani answered 24/10, 2016 at 14:40 Comment(2)
did you ever figure this out?Cosgrove
Sadly no, I tried in several different ways with jackson with no success. I fell back to apache commons csv. I can dig out an example for that if it's of any help to you.Pani
H
23

It's possible with a use of mixins, since you want to use those name only for csv export:

Let assume you have id field in your Pojo class with a getter. Then you Create PojoFormat abstract class:

public abstract class PojoFormat {
    @JsonProperty("Report Id")
    abstract Integer getId();
}

And in your code use it like that:

    CsvMapper mapper = new CsvMapper();

    mapper.addMixIn(Pojo.class, PojoFormat.class);
    CsvSchema schema = mapper.schemaFor(Pojo.class).withHeader();
    mapper.writer(schema).writeValueAsString(objects);
Hearthstone answered 18/7, 2017 at 10:6 Comment(2)
@Hearthstone I apologize for not noticing your reply all this time. I marked your answer as accepted based on the votes and comments on your post.Pani
What about csv import?Balliol

© 2022 - 2024 — McMap. All rights reserved.