400

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

我怎样才能只@JsonIgnore申请序列化而不是反序列化?我正在使用 Spring JSONView,所以我对ObjectMapper.

我尝试过的事情:

  1. 添加@JsonIgnore到属性
  2. 仅添加@JsonIgnoregetter 方法
4

8 回答 8

603

具体如何执行此操作取决于您使用的 Jackson 版本。这在1.9版本左右发生了变化,在此之前,您可以通过添加@JsonIgnore到 getter 来做到这一点。

您尝试过的:

仅在 getter 方法上添加 @JsonIgnore

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

READ_ONLYJackson的最新版本WRITE_ONLYJsonProperty. 因此,您还可以执行以下操作:

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;

文档可以在这里找到。

于 2012-09-20T01:53:47.410 回答
113

为了做到这一点,我们只需要两个注解:

  1. @JsonIgnore
  2. @JsonProperty

@JsonIgnore在类成员及其 getter@JsonProperty及其 setter 上使用。示例插图将有助于做到这一点:

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;
    }
}
于 2014-12-09T18:37:02.323 回答
96

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

@JsonProperty(access = Access.WRITE_ONLY)
private String myField;

即使存在 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

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

于 2015-12-08T14:22:34.190 回答
16

In my case, I have Jackson automatically (de)serializing objects that I return from a Spring MVC controller (I am using @RestController with Spring 4.1.6). I had to use com.fasterxml.jackson.annotation.JsonIgnore instead of org.codehaus.jackson.annotate.JsonIgnore, as otherwise, it simply did nothing.

于 2015-06-22T15:45:53.693 回答
4

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

例子:

@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
    String foo;
    String bar;
}

foo和都bar填充在对象中,但只有 foo 被写入响应正文。

于 2019-12-10T23:11:33.050 回答
3
"user": {
        "firstName": "Musa",
        "lastName": "Aliyev",
        "email": "klaudi2012@gmail.com",
        "passwordIn": "98989898", (or encoded version in front if we not using https)
        "country": "Azeribaijan",
        "phone": "+994707702747"
    }

@CrossOrigin(methods=RequestMethod.POST)
@RequestMapping("/public/register")
public @ResponseBody MsgKit registerNewUsert(@RequestBody User u){

        root.registerUser(u);

    return new MsgKit("registered");
}  

@Service
@Transactional
public class RootBsn {

    @Autowired UserRepository userRepo;

    public void registerUser(User u) throws Exception{

        u.setPassword(u.getPasswordIn());
        //Generate some salt and  setPassword (encoded -  salt+password)
        User u=userRepo.save(u);

        System.out.println("Registration information saved");
    }

}

    @Entity        
@JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
                    public class User implements Serializable {
                        private static final long serialVersionUID = 1L;

                        @Id
                        @GeneratedValue(strategy=GenerationType.AUTO)
                        private Long id;

                        private String country;

                        @Column(name="CREATED_BY")
                        private String createdBy;

                        private String email;

                        @Column(name="FIRST_NAME")
                        private String firstName;

                        @Column(name="LAST_LOGIN_DATE")
                        private Timestamp lastLoginDate;

                        @Column(name="LAST_NAME")
                        private String lastName;

                        @Column(name="MODIFICATION_DATE")
                        private Timestamp modificationDate;

                        @Column(name="MODIFIED_BY")
                        private String modifiedBy;

                        private String password;

                        @Transient
                        private String passwordIn;

                        private String phone;

                        @Column(name="RECORD_DATE")
                        private Timestamp recordDate;

                        private String salt;

                        private String status;

                        @Column(name="USER_STATUS")
                        private String userStatus;

                        public User() {
                        }
                // getters and setters
                }
于 2016-05-01T11:13:20.033 回答
2

您可以在类级别使用 @JsonIgnoreProperties 并将您想要在 json 中的变量放入“值”参数中。对我来说很好。

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}
于 2020-07-06T08:54:37.117 回答
2

你也可以这样做:

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

它对我有用

于 2020-08-22T16:28:58.983 回答