Jackson ObjectMapper忽略所有没有注释的属性

Int*_*eep 3 java json jackson mongo-jackson-mapper

我的目标是将jsonObject转换为Class。我只想添加在Class中注释的字段。示例:json对象包含50个字段。类有4个字段。我只想映射确切的4个字段,而不在类中添加46个附加忽略。

JSON:

{
  "id": "1",
  "name": "John",
  "Address": "Some Address 7009",
}
Run Code Online (Sandbox Code Playgroud)

类:

public static class User {
    Integer id;
    String name;

    public User (@JsonProperty("id")Integer id, @JsonProperty("name")String name {
            this.id= id;
            this.name= name;
    }
    ....
}
Run Code Online (Sandbox Code Playgroud)

用户类别没有地址字段。我的目标是排除它,因为它没有注释。

cas*_*lin 5

使用注释您的班级@JsonIgnoreProperties,如下所示:

@JsonIgnoreProperties(ignoreUnknown = true)
public class User {
    ...
}
Run Code Online (Sandbox Code Playgroud)

ignoreUnknown为is时true,所有无法识别的属性(即没有设置器或创建者都接受它们)都将在没有警告的情况下被忽略(尽管仍会调用未知属性的处理程序)(如果有的话)。