我有一个名为password的字段,端点可以接收它。但它不能作为响应发回,也不能持久保存在数据库中
类如下所示-
public class ShortURL {
@Pattern(regexp="^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]")
private String url;
@Size(min=8,max=16)
@Transient
private String password = null;
private boolean isPasswordProtected = false;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isPasswordProtected() {
return isPasswordProtected;
}
public void setPasswordProtected(boolean isPasswordProtected) {
this.isPasswordProtected = isPasswordProtected;
}
public ShortURL(
@Pattern(regexp = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]") String url,
@Size(min = 8, max = 16) String password, boolean isPasswordProtected) {
super();
this.url = url;
this.password = password;
this.isPasswordProtected = isPasswordProtected;
}@Transient工作正常。但是在@Transient之后添加@JsonIgnore会导致问题-
Type definition error: [simple type, class java.lang.String];
nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException:
No fallback setter/field defined for creator property 'password'"我如何实现我的意图?
发布于 2018-04-24 01:25:18
这取决于你的杰克逊版本。
在1.9版本之前,您可以将@JsonIgnore添加到password的getter中,并将@JsonProperty添加到password字段的setter中。
杰克逊的Recent versions为@JsonProperty提供了READ_ONLY和WRITE_ONLY注释参数,如下所示:
@JsonProperty(access = Access.READ_ONLY)
private String password;发布于 2018-04-24 01:37:42
是的,你可以使用@JsonIgnore让jackson在发送用户响应时忽略它,但是。您应该遵循一些特定的最佳实践。
永远不要将实体直接暴露给端点,而最好是有一个包装器,即DTO,它将你的实体转换成所需的响应。例如。在你的情况下
public class ShortURL {
@Pattern(regexp="^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]")
private String url;
@Size(min=8,max=16)
private String password;
private boolean isPasswordProtected;
}//这里是dto,您可以在其中创建一个参数化构造函数,并根据您想要设置的字段相应地调用它。
public class ShortURLDTO {
private String url;
public ShortURLDTO(String url){
this.url=url
}
}https://stackoverflow.com/questions/49986253
复制相似问题