自定义反序列化工具类
在实体类中实现了 implements Serializable 序列化 还实现了 UserDetails 对传入的字段 authorities 返序列化失败
对字段 authorities 单独自定义反序列化工具类
下面是我的报错:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of
org.springframework.security.core.GrantedAuthority
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
at [Source: (PushbackInputStream); line: 1, column: 442] (through reference chain: com.abin.pojo.Admin[“authorities”]->java.util.ArrayList[2])
上代码:CustomAuthorityDeserializer.class
/**
* 自定义 Authority解析器
*/
public class CustomAuthorityDeserializer extends JsonDeserializer { //
@Override
public Object deserialize(
JsonParser jsonParser, //JSON解析
DeserializationContext deserializationContext) // 上下文
throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec(); //得到Object对象
JsonNode jsonNode = mapper.readTree(jsonParser); // readTree得到TreeNode对象,JsonNode有实现TreeNode接口
List<GrantedAuthority> grantedAuthorities = new LinkedList<>(); // 返回
Iterator<JsonNode> elements = jsonNode.elements(); // 得到迭代器
while (elements.hasNext()) {
JsonNode next = elements.next();
JsonNode authority = next.get("authority"); //需要对这个字段进行解析
grantedAuthorities.add(new SimpleGrantedAuthority(authority.asText()));
}
return grantedAuthorities;
}
}
在用的地方使用:重写 UserDetails 类的方法 getAuthorities()
这个方法得到这个用户拥有的权限: 加上 @JsonDeserialize 注解来使用
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
@Override
@JsonDeserialize(using = CustomAuthorityDeserializer.class) // 用注解 使用
public Collection<? extends GrantedAuthority> getAuthorities() {
List<SimpleGrantedAuthority> authorities = roles.stream().map(role -> new SimpleGrantedAuthority(role.getName())).collect(Collectors.toList());
return authorities;
}