仅在序列化期间使用@JsonIgnore,但不反序列化

chu*_*ubs 298 java spring json annotations jackson

我有一个发送到服务器和从服务器发送的用户对象.当我发出用户对象时,我不想将散列密码发送给客户端.所以我添加@JsonIgnore了密码属性,但这也阻止了它被反序列化为密码,这使得在没有密码时很难注册用户.

我怎样才能@JsonIgnore应用于序列化而不是反序列化?我正在使用Spring JSONView,所以我没有很多控制权ObjectMapper.

我试过的事情:

  1. 加入@JsonIgnore物业
  2. @JsonIgnore仅添加getter方法

pb2*_*b2q 440

究竟如何做到这一点取决于你正在使用的杰克逊版本.这在版本1.9中发生了变化,在此之前,您可以通过添加@JsonIgnore到getter 来实现此目的.

你试过的:

仅在getter方法上添加@JsonIgnore

执行此操作,并将@JsonProperty JSON"密码"字段名称的特定注释添加到对象密码的setter方法中.

更新版本的杰克逊已添加READ_ONLYWRITE_ONLY注释参数JsonProperty.所以你也可以这样做:

@JsonProperty(access = Access.WRITE_ONLY)
private String password;
Run Code Online (Sandbox Code Playgroud)

可以在这里找到文档.

  • `@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)` (11认同)
  • 此外,请确保从字段本身中删除@JsonProperty,否则它将覆盖您的getter/setter注释 (3认同)
  • 对杰克逊JSON https://gist.github.com/thurloat/2510887忽略**反序列化** (2认同)
  • 请注意,“JsonProperty”是“com.fasterxml.jackson.annotation.JsonProperty”,“Access”是“com.fasterxml.jackson.annotation.JsonProperty.Access”而不是“javax.persistence.Access”,如果您编写了类似的代码`import javax.persistence.*;` 的 Access 可能不是你想要的。 (2认同)

Bal*_*yan 94

为了实现这一点,我们需要的只是两个注释:

  1. @JsonIgnore
  2. @JsonProperty

使用@JsonIgnore类成员和其吸气剂上.@JsonProperty在其二传手上使用.

示例说明将有助于执行此操作:

class User {

    // More fields here
    @JsonIgnore
    private String password;

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    @JsonProperty
    public void setPassword(final String password) {
        this.password = password;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 它甚至在场上没有`@JsonIgnore`也能工作. (3认同)
  • 这是 jackson 2.6.4 唯一对我有用的东西。我尽力使用 @JsonProperty(access = Access.WRITE_ONLY) 但它对我不起作用。 (2认同)

Dan*_*eer 73

从版本2.6开始:更直观的方法是com.fasterxml.jackson.annotation.JsonProperty在字段上使用注释:

@JsonProperty(access = Access.WRITE_ONLY)
private String myField;
Run Code Online (Sandbox Code Playgroud)

即使存在getter,也会从序列化中排除字段值.

JavaDoc说:

/**
 * Access setting that means that the property may only be written (set)
 * for deserialization,
 * but will not be read (get) on serialization, that is, the value of the property
 * is not included in serialization.
 */
WRITE_ONLY
Run Code Online (Sandbox Code Playgroud)

如果您需要反过来,只需使用Access.READ_ONLY.

  • 我不明白为什么投票这么少,这是解决这个问题的优雅方法,很有魅力。无需注释 getter、setter 和 field。唯有田野。谢谢。 (3认同)

Ale*_*ley 13

在我的情况下,我让Jackson自动序列化/反序列化我从Spring MVC控制器返回的对象(我在Spring 4.1.6中使用@RestController).我必须使用com.fasterxml.jackson.annotation.JsonIgnore而不是org.codehaus.jackson.annotate.JsonIgnore,否则它什么也没做.


小智 8

allowSetters = true处理此问题的另一种简单方法是在注释中使用参数。这将允许密码反序列化到您的 dto 中,但不会将其序列化到使用 contains 对象的响应正文中。

例子:

@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
    String foo;
    String bar;
}
Run Code Online (Sandbox Code Playgroud)

foobar填充在对象中,但只有 foo 写入响应正文中。