Home > Net >  How to ignore nested fields from parent class?
How to ignore nested fields from parent class?

Time:10-08

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)

CodePudding user response:

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

CodePudding user response:

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.

  • Related