想要隐藏杰克逊映射到JSON的对象的某些字段 [英] Want to hide some fields of an object that are being mapped to JSON by Jackson
问题描述
我有一个User类要使用Jackson映射到JSON。
I have a User class that I want to map to JSON using Jackson.
public class User {
private String name;
private int age;
prviate int securityCode;
// getters and setters
}
我映射此使用 -
User user = getUserFromDatabase();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
我不想映射 securityCode
变量。有没有办法配置映射器以便它忽略这个字段?
I don't want to map the securityCode
variable. Is there any way of configuring the mapper so that it ignores this field?
我知道我可以编写自定义数据映射器或使用Streaming API但是我想知道是否可以通过配置来实现吗?
I know I can write custom data mappers or use the Streaming API but I would like to know if it possible to do it through configuration?
推荐答案
您有两种选择:
-
杰克逊的工作场所是吸气者。因此,您可以删除要在JSON中省略的字段的getter。 (如果你不需要在其他地方使用getter。)
Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
或者,你可以使用 @JsonIgnore
杰克逊的注释关于该字段的getter方法,你会看到没有这样的键值对结果JSON。
Or, you can use the @JsonIgnore
annotation of Jackson on getter method of that field and you see there in no such key-value pair in resulted JSON.
@JsonIgnore
public int getSecurityCode(){
return securityCode;
}
这篇关于想要隐藏杰克逊映射到JSON的对象的某些字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!