bbd127
bbd127

Reputation: 175

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.

Upvotes: 12

Views: 9178

Answers (1)

Piotr
Piotr

Reputation: 694

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);

Upvotes: 23

Related Questions