gpt4 book ai didi

java - 在从 Spring MVC 作为 JSON 发送时动态忽略 Java 对象中的字段

转载 作者:IT老高 更新时间:2023-10-28 11:39:04 26 4
gpt4 key购买 nike

我有这样的模型类,用于 hibernate

@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {

private Integer userId;
private String userName;
private String emailId;
private String encryptedPwd;
private String createdBy;
private String updatedBy;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "UserId", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}

public void setUserId(Integer userId) {
this.userId = userId;
}

@Column(name = "UserName", length = 100)
public String getUserName() {
return this.userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

@Column(name = "EmailId", nullable = false, length = 45)
public String getEmailId() {
return this.emailId;
}

public void setEmailId(String emailId) {
this.emailId = emailId;
}

@Column(name = "EncryptedPwd", length = 100)
public String getEncryptedPwd() {
return this.encryptedPwd;
}

public void setEncryptedPwd(String encryptedPwd) {
this.encryptedPwd = encryptedPwd;
}

public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}

@Column(name = "UpdatedBy", length = 100)
public String getUpdatedBy() {
return this.updatedBy;
}

public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}

在 Spring MVC Controller 中,使用 DAO,我能够获取对象。并作为 JSON 对象返回。

@Controller
public class UserController {

@Autowired
private UserService userService;

@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
@ResponseBody
public User getUser(@PathVariable Integer userId) throws Exception {

User user = userService.get(userId);
user.setCreatedBy(null);
user.setUpdatedBy(null);
return user;
}
}

View 部分是使用 AngularJS 完成的,所以它会得到这样的 JSON

{
"userId" :2,
"userName" : "john",
"emailId" : "john@gmail.com",
"encryptedPwd" : "Co7Fwd1fXYk=",
"createdBy" : null,
"updatedBy" : null
}

如果我不想设置加密密码,我也会将该字段设置为空。

但我不想这样,我不想将所有字段发送到客户端。如果我不想发送密码、updatedby、createdby 字段,我的结果 JSON 应该是这样的

{
"userId" :2,
"userName" : "john",
"emailId" : "john@gmail.com"
}

我不想发送给来自其他数据库表的客户端的字段列表。所以它会根据登录的用户而改变。我该怎么做?

我希望你有我的问题。

最佳答案

@JsonIgnoreProperties("fieldname") 注释添加到您的 POJO。

或者您可以在反序列化 JSON 时在要忽略的字段名称前使用 @JsonIgnore。示例:

@JsonIgnore
@JsonProperty(value = "user_password")
public String getUserPassword() {
return userPassword;
}

GitHub example

关于java - 在从 Spring MVC 作为 JSON 发送时动态忽略 Java 对象中的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23101260/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com