【问题标题】:GrantedAuthority caused JSON mapping exceptionGrantedAuthority 导致 JSON 映射异常
【发布时间】:2023-04-08 19:07:01
【问题描述】:

面对这个

无法写入 JSON:org.hibernate.collection.internal.PersistentSet 无法转换为 org.springframework.security.core.GrantedAuthority;嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: org.hibernate.collection.internal.PersistentSet 不能转换为 org.springframework.security.core.GrantedAuthority (通过引用链:java.util.ArrayList[0]-> com.example.springboot.model.User["authorities"])

尝试将用户列表传递到我的 html 页面时出错。

我想关键是角色类的序列化错误,但我不知道如何解决这个问题。

两个类都在下面。 User 和 Role 类与 ManytoMany 模型相连。

@Entity
@Table(name = "users_for_spring_crud")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class User implements UserDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "name")
private String name;

@Column(name = "email")
private String email;

@Column(name = "password")
private String password;

@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
@Entity
@Table(name = "roles")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
public class Role implements GrantedAuthority {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "role_id")
private long id;

@Column(name = "role")
private String roleName;

@ManyToMany(mappedBy = "roles")
@JsonIgnore
List<User> users;

如果需要,还有一个控制器类中的方法。

@GetMapping(value = "/admin", produces = {MediaType.APPLICATION_JSON_VALUE})
@ResponseBody
public List<User> showUsersTable(@ModelAttribute("user") User user){
List<User> listUsers = userService.listUsers();
return listUsers;

考虑编写自定义序列化程序,但不知道它应该如何工作。

【问题讨论】:

    标签: java json spring


    【解决方案1】:

    一如既往,关键在于关注您自己的类,尤其是覆盖方法

    正确版本的 getAuthorities() 方法解决了问题

    @Override
    public Collection<GrantedAuthority> getAuthorities() {
         List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (Role role: roles) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            role.getPrivileges().stream()
            .map(p -> new SimpleGrantedAuthority(p.getRoleName()))
            .forEach(grantedAuthorities::add);
        }
        return grantedAuthorities;
    }
    

    感谢您的关注。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 2022-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多