简体   繁体   中英

Jackson ObjectMapper ignore all properties that has no annotation

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM