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

新手上路,请多包涵

我有这样的模型类,用于休眠

@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
}

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

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

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

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

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

原文由 iCode 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 936
2 个回答

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

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

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

GitHub 示例

原文由 user3145373 ツ 发布,翻译遵循 CC BY-SA 4.0 许可协议

我可以动态地做吗?

创建视图类:

 public class View {
    static class Public { }
    static class ExtendedPublic extends Public { }
    static class Internal extends ExtendedPublic { }
}

注释你的模型

@Document
public class User {

    @Id
    @JsonView(View.Public.class)
    private String id;

    @JsonView(View.Internal.class)
    private String email;

    @JsonView(View.Public.class)
    private String name;

    @JsonView(View.Public.class)
    private Instant createdAt = Instant.now();
    // getters/setters
}

在控制器中指定视图类

@RequestMapping("/user/{email}")
public class UserController {

    private final UserRepository userRepository;

    @Autowired
    UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    @JsonView(View.Internal.class)
    public @ResponseBody Optional<User> get(@PathVariable String email) {
        return userRepository.findByEmail(email);
    }

}

数据示例:

 {"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}

UPD:请记住,使用实体作为响应并不是最佳做法。最好为每种情况使用不同的 DTO,并使用 modelmapper 填充它们

原文由 Hett 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题