java - 如何修复 Spring 中的 JSON 解码错误?
问题描述
我正在通过 REST 发送一个包含一组对象的用户SimpleGrantedAuthority
对象。在接收方,我遇到了一个例外:
org.springframework.core.codec.DecodingException:JSON 解码错误:无法构造实例
org.springframework.security.core.authority.SimpleGrantedAuthority
(尽管至少存在一个 Creator):无法从 Object 值反序列化(没有基于委托或基于属性的 Creator);
我正在使用 Spring Boot 2.1.2 提供的默认 JSON 映射器。在接收端,我使用的是 WebFlux 的 WebClient(在本例中为 WebTestClient)。
谁能向我解释为什么会出现此错误以及如何解决?
解决方案
SimpleGrantedAuthority
不适合与 Jackson 进行自动映射;它没有无参数构造函数,也没有该authority
字段的设置器。
所以它需要一个自定义的反序列化器。像这样的东西:
class SimpleGrantedAuthorityDeserializer extends StdDeserializer<SimpleGrantedAuthority> {
public SimpleGrantedAuthorityDeserializer() {
super(SimpleGrantedAuthority.class);
}
@Override
public SimpleGrantedAuthority deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode tree = p.getCodec().readTree(p);
return new SimpleGrantedAuthority(tree.get("authority").textValue());
}
}
像这样在全球范围内向 Jackson 注册它:
objectMapper.registerModule(new SimpleModule().addDeserializer(
SimpleGrantedAuthority.class, new SimpleGrantedAuthorityDeserializer()));
或使用以下方式注释字段:
@JsonDeserialize(using = SimpleGrantedAuthorityDeserializer.class)
注意:您不需要序列化程序,因为SimpleGrantedAuthority
有getAuthority()
杰克逊可以使用的方法。
推荐阅读
- javascript - 在 WordPress ajax 中使用 sendBeacon
- python - 用于特征重要性或选择的 sklearn 算法,它接受名义分类变量而不对其进行编码
- discord.py - discord.py 中的反应
- mysql - 我们可以在 mysql 中的日期函数上使用算术运算符(+、-.* 或 /)吗?
- android - viewpager2 不会一直设置当前项目
- java - Retrofit2 永远不会调用 Gson 自定义反序列化器
- arrays - 获取数组onClick VUE3中对象的索引
- hashicorp-vault - 无法通过 CLI 登录 Vault
- reactjs - 我们在哪里获得 React.js 中 render 方法中的 props
- python - Python & Pandas:使用 pd.json_normalize 展平嵌套的 json