Jackson ObjectMapper ignore all properties that has no annotation

IntoTheDeep picture IntoTheDeep · Oct 4, 2016 · Viewed 9.8k times · Source

My target is is to convert jsonObject to Class. I want to add only fields that are anotated in Class. Example: json object holds 50 fields. Class has 4 fields. I want to map only exact 4 fields without adding 46 addition ignores in class.

JSON:

{
  "id": "1",
  "name": "John",
  "Address": "Some Address 7009",
}

Class:

public static class User {
    Integer id;
    String name;

    public User (@JsonProperty("id")Integer id, @JsonProperty("name")String name {
            this.id= id;
            this.name= name;
    }
    ....
}

User class has no address field. My target is to exclude it, because it has no annotation.

Answer

cassiomolin picture cassiomolin · Oct 4, 2016

Annotate your class with @JsonIgnoreProperties, as following:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    ...
}

When ignoreUnknown is true, all properties that are unrecognized (that is, there are no setters or creators that accept them) are ignored without warnings (although handlers for unknown properties, if any, will still be called) without exception.