Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson-dataformat-csv - are custom column names possible?

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.

like image 308
bbd127 Avatar asked Oct 24 '16 14:10

bbd127


1 Answers

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);
like image 196
Piotr Avatar answered Nov 10 '22 20:11

Piotr