一尘不染

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

hibernate

我有这样的模型类,用于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控制器中,使用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;
    }
}

视图部分是使用AngularJS完成的,因此它将获得像这样的JSON

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

如果我不想设置加密的密码,则将该字段也设置为null。

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

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

我不想发送给其他数据库表的客户端的字段列表。因此,它将根据登录的用户进行更改。我该怎么做?

我希望你能回答我的问题。


阅读 302

收藏
2020-06-20

共1个答案

一尘不染

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

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

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

GitHub范例

2020-06-20