Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omitting fields when using Jackson CsvMapper to serialize POJOs

I'm serialising a POJO to CSV using jackson. My problem is that I can't work out how to ommit certain fields when serializing. I don't want to have to annotate the POJO as it would affect the JSON and XML serialisation which requires those fields. For example

public class POJO {
  public string field1; //required by JSON and CSV
  public string field2; //only required by JSON
}

Is there a way to achieve this?

like image 803
tom Avatar asked Oct 17 '13 13:10

tom


1 Answers

What worked for me was setting the CsvMapper setting com.fasterxml.jackson.core.JsonGenerator.Feature.IGNORE_UNKNOWN to true

CsvMapper mapper = new CsvMapper(); //com.fasterxml.jackson.dataformat.csv.CsvMapper
MAPPER.configure(Feature.IGNORE_UNKNOWN, true);

adding the desired columns to the schema.

CsvSchema schema = CsvSchema.builder();
    .addColumn("A")
    .addColumn("C")
    .build();

for my POJO

public class MyClass{

    @JsonProperty("A")
    private string a;

    @JsonProperty("B")
    private string b;

    @JsonProperty("C")
    private string c;

    //getters setters

}

To get the CSV string I did this:

List<MyClass> list = new MyClass();
MyClass row = new MyClass();

row.setA("Value A");
row.setB("Value B");
row.setC("Value C");

list.add(row);

ObjectWriter ow = mapper.writer(schema);
String csv = ow.writeValueAsString(list);

Output (withHeaders):

A,C
"Value A","Value C"
like image 165
Cheloide Avatar answered Oct 28 '22 02:10

Cheloide