Drex
Drex

Reputation: 3831

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

Upvotes: 0

Views: 2744

Answers (2)

ray
ray

Reputation: 1670

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.

Upvotes: 1

João Dias
João Dias

Reputation: 17460

  1. To my knowledge no. You need to place the @JsonIgnoreProperties in nested classes as well.
  2. Take a look at [JSON Views][1]. With it, you can tell which properties to include in each view. You could have 1 view:
public class Views {
    public static class Public {
    }
}

Then in your model you would need to annotate the properties you want to be avialble with @JsonView(Views.Public.class). Finally, in your endpoints, you would use @JsonView(Views.Public.class).

Upvotes: 0

Related Questions