如何修复 Spring 中的 JSON 解码错误?

OCP*_*CPi 3 java spring jackson spring-webflux

我正在通过包含一组对象的 REST 发送一个用户SimpleGrantedAuthority对象。在接收方,我遇到了一个例外:

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

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

任何人都可以向我解释为什么我会收到此错误以及如何解决它?

rus*_*tyx 7

SimpleGrantedAuthority不适合与 Jackson 自动映射;它没有无参数构造函数,也没有该authority字段的setter 。

所以它需要一个自定义的解串器。像这样的东西:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

像这样在全球范围内向 Jackson 注册:

objectMapper.registerModule(new SimpleModule().addDeserializer(
                      SimpleGrantedAuthority.class, new SimpleGrantedAuthorityDeserializer()));
Run Code Online (Sandbox Code Playgroud)

或使用以下注释对字段进行注释:

@JsonDeserialize(using = SimpleGrantedAuthorityDeserializer.class)
Run Code Online (Sandbox Code Playgroud)

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