简体   繁体   English

我怎么能忽略json响应中的字段?

[英]How could I ignore a field in json response?

@Column(name = "password", nullable = false)
@JSonIgnore
private String password;

I have given the above field in my model class, but It did not work for the POST method. 我在我的模型类中给出了上面的字段,但它对POST方法不起作用。

Error:null value in column "password" violates not-null constraint 错误:“password”列中的空值违反了非空约束

Add @JsonIgnore only on getter method . 在getter方法上添加@JsonIgnore。

@Column(name = "password", nullable = false)
private String password;

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

public void setPassword(String password) {
    this.password = password;
}

or 要么

@JsonProperty(access = Access.WRITE_ONLY)
@Column(name = "password", nullable = false)
private String password;

I had solved the problem. 我解决了这个问题。 This was my old code: @Column(name = "password", nullable = false) 这是我的旧代码: @Column(name = "password", nullable = false)

`@JSonIgnore`

`private String password;` 

Instead of JSonIgnore, we can use JSonProperty. 我们可以使用JSonProperty代替JSonIgnore。 Below is the code: 以下是代码:

This is the new code: @Column(name = "password", nullable = false) 这是新代码: @Column(name = "password", nullable = false)

@JsonProperty(access = Access.WRITE_ONLY)

private String password;

Thanks to everyone for helping... 感谢大家的帮助......

您已将字段设置为nullable = false - 这意味着密码不能为空,因此某些代码验证不允许您将空值传递给password

I think you're mixing up the request and the response: 我想你正在混淆请求和回复:

  • @JsonIgnore will ignore the field when it gets parsed to JSON as a response object. 当@JsonIgnore被解析为JSON作为响应对象时,它将忽略该字段。 (Eg for some API call) (例如,对于一些API调用)
  • If you POST data which should be creating an object with a nonnull password, the request must have this parameter. 如果POST POST应该使用非空密码创建对象的数据,则该请求必须具有此参数。 @JsonIgnore does not change anything to that. @JsonIgnore不会改变任何东西。

If you want to have the POST data being valid while not sending the password, you will need to create an object which you can save apart from the password. 如果要在不发送密码的情况下使POST数据有效,则需要创建一个可以与密码分开保存的对象。 This could be a saveable superclass, where the subclass has only the password, or just another class which has a relation to another class which holds the password field. 这可以是一个可保存的超类,其中子类只有密码,或者只是另一个与另一个拥有密码字段的类有关系的类。

If you don't want the separate class, you'll either have to add the password to your request or change nullable attribute in the @Column annotation to true. 如果您不想要单独的类,则必须将密码添加到请求中,或者将@Column注释中的nullable属性更改为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM