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?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With