Search code examples
javajacksonjson-deserialization

How to ignore nested fields from parent class?


I have a JSON model with A child property that has lots of fields which I would like to ignore. For example

{
    "id": 1,
    "preference": {
        "subproperty1": "dummy",
        "subproperty2": "dummy",
        "subproperty3": "dummy",
        ...
        "subproperty40": "dummy",
    },
    "property1": "dummy",
    "property2": "dummy",
    ...
    "property30": "dummy",
}

My expected deserialized result would be something look like

{
    "id": 1,
    "preference": {
        "subproperty1": "dummy",
        "subproperty2": "dummy",
    },
    "property1": "dummy",
    "property2": "dummy"
}

Meaning I would like to ignore lots of fields in my current and nested class, I know there is a @JsonIgnoreProperties to use such as

@JsonIgnoreProperties({"name", "property3", "property4", ..., "property30"})
@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
protected static class MixInMyClass {

}
...
objectMapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MixInMyClass.class);
  • Question1: how could I ignore my nested fields (e.g, subproperty3, subproperty4... subproperty30) in "preference" on top of MixInMyClass?

  • Question2: is there any easier way like a JsonRequired which plays as the opposite behavior and only allows certain needed fields in? So I don't need to have lots of unwanted fields as in jsonIgnore, but just few items like (id, property1, property2)


Solution

  • You can simply fix this by annotating @JsonIgnoreProperties(ignoreUnknown = true).

    Here is an example,

    @JsonIgnoreProperties(ignoreUnknown = true)
    class YouMainClass {
        private Integer id;
        private Preference preference;
        private String property1;
        private String property2;
    
        // getters & setters
    }
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    class Preference {
        private String property1;
        private String property2;
    
        // getters & setters
    }
    

    Use this YouMainClass to deserialize the JSON. All the unknow/unwanted properties will be ignored when deserializing.