首页 > 解决方案 > 如何修复 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)。

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

标签: javaspringjacksonspring-webflux

解决方案


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)

注意:您不需要序列化程序,因为SimpleGrantedAuthoritygetAuthority()杰克逊可以使用的方法。


推荐阅读