【问题标题】:How to fix JSON decoding error in Spring?如何修复 Spring 中的 JSON 解码错误?
【发布时间】:2019-06-09 14:37:54
【问题描述】:

我正在通过 REST 发送一个用户对象,其中包含一组 SimpleGrantedAuthority 对象。在接收方,我遇到了一个异常:

org.springframework.core.codec.DecodingException: JSON解码错误: 无法构造实例 org.springframework.security.core.authority.SimpleGrantedAuthority (尽管至少存在一个 Creator):不能从 Object 反序列化 值(无委托或基于属性的创建者);

我正在使用 Spring Boot 2.1.2 提供的默认 JSON 映射器。在接收端,我使用的是 WebFlux 的 WebClient(本例中为 WebTestClient)。

谁能向我解释为什么会出现此错误以及如何解决?

【问题讨论】:

标签: java spring jackson spring-webflux


【解决方案1】:

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() 方法,Jackson 可以使用该方法。

【讨论】:

  • 非常感谢!像魅力一样工作。
  • 如果你要注释签名public Collection&lt;GrantedAuthority&gt; getAuthorities(),请确保使用contentUsing,所以@JsonDeserialize(contentUsing = SimpleGrantedAuthorityDeserializer.class),否则反序列化器会立即将整个集合节点反序列化。
猜你喜欢
  • 1970-01-01
  • 2013-03-12
  • 2020-06-18
  • 2021-12-01
  • 1970-01-01
  • 2017-03-11
  • 2021-06-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多