在 Dropwizard 中隐藏模型上的字段的最佳方法是什么? (如果我希望能够通过 Jackson 反序列化该字段,但在序列化时隐藏它)
例如,如果我有以下模型:
class User {
private String secret;
private String username;
}
我希望能够通过调用 new ObjectMapper().readValue()
创建一个带有 secret 的用户,但我想在序列化为 JSON 时隐藏 secret 字段。
最佳答案
在属性前添加@JsonIgnore
注解
或者您可以添加@JsonIgnoreProperties
注释并指定要排除的字段
public class Foo{
@JsonIgnore
private String bar;
...
}
或
@JsonIgnoreProperties(value = { "bar" })
public class Foo {
private String bar;
...
}
或者如果您只想在序列化时忽略此字段,而不是在反序列化时忽略该字段
public class Foo{
private String bar;
...
@JsonIgnore
public String getBar(){
return bar;
}
public void setBar(String bar){
this.bar = bar;
}
}
关于jackson - Dropwizard隐藏json字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21770773/