Home > Mobile >  Exclude colums (fields) using Jackson CsvMapper to serialize POJO
Exclude colums (fields) using Jackson CsvMapper to serialize POJO

Time:09-02

I have a Java class and i want to serialize it into CSV using jackson. In addition i want to exclude from the csv a single field base on a external property.

I have tried using all features provides by jackson like Feature.IGNORE_UNKNOWN=true or @JsonIgnoreProperties(ignoreUnknown = true) on my data class, csvMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) but none of them works. I still receive the exception column not found in schema when not all columns are declared in the schema. Code works fine in the other case.

Here i upload my implementation

    public class MyClass{
        @JsonProperty("A")
        private string a;
    
        @JsonProperty("B")
        private string b;
    
        @JsonProperty("C")
        private string c;  
    }

CsvMapper mapper = new CsvMapper();
mapper.configure(Feature.IGNORE_UNKNOWN, true);
CsvSchema csvSchema;
if (disable = true) {
    schema = CsvSchema.builder()
      .addColumn("A")
      .addColumn("C")
      .build()
} else {
    schema = CsvSchema.builder()
      .addColumn("A")
      .addColumn("B")
      .addColumn("C")
      .build()
}

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

CodePudding user response:

Using Feature.IGNORE_UNKNOWN=true or @JsonIgnoreProperties(ignoreUnknown = true) will help when you want to deserialize JSON into your Java class.

For example, this will be useful when you're implementing the REST API and in the POST method dedicated to creating new objects, you want to ignore all invalid/incorrect fields sent to you by the user and process only the valid ones instead of returning the 400/500 error.

In your case, you just need to put the @JsonIgnore annotation on the field in your Java class, which you want to exclude during the serialization. This is an example of excluding the «a» property:

public class MyClass {
    @JsonIgnore
    @JsonProperty("A")
    private String a;

    @JsonProperty("B")
    private String b;

    @JsonProperty("C")
    private String c;
}

This should also be useful in cases when you want to exclude some private and sensitive information from application logs, like passwords, PII, PHI, etc.

CodePudding user response:

use @JsonIgnore on top of property. Ex:

import com.fasterxml.jackson.annotation.JsonIgnore;
@Validated
@Data
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Builder
public class MyResponseModel {
...
        @JsonIgnore
        private String createBy;
        ...
}
  • Related