Issues while deserializing exception/throwable using Jackson in Java

前端 未结 6 1771
無奈伤痛
無奈伤痛 2021-02-19 13:42

I am facing issues while deserializing Exception and Throwable instances using Jackson (version 2.2.1). Consider the following snippet:



        
6条回答
  •  北荒
    北荒 (楼主)
    2021-02-19 14:24

    I've had a similar issue. I'm using this code now, and it allows me to serialize and deserialize exceptions with proper types (i.e. a RuntimeException will be a RuntimeException again :)):

    public static ObjectMapper createObjectMapper() {
        ObjectMapper mapper = new ObjectMapper(null, null, new DefaultDeserializationContext.Impl(
                new BeanDeserializerFactory(new DeserializerFactoryConfig()) {
                    private static final long serialVersionUID = 1L;
    
                    @Override
                    public JsonDeserializer buildThrowableDeserializer(
                            DeserializationContext ctxt, JavaType type, BeanDescription beanDesc)
                            throws JsonMappingException {
                        return super.buildBeanDeserializer(ctxt, type, beanDesc);
                    }
    
                }));
    
        mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
        mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    
        mapper.addMixIn(Throwable.class, ThrowableMixin.class);
        mapper.addMixIn(StackTraceElement.class, StackTraceElementMixin.class);
    
        return mapper;
    }
    
    @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
    @JsonAutoDetect(fieldVisibility = Visibility.ANY)
    @JsonIgnoreProperties({ "message", "localizedMessage", "suppressed" })
    abstract class ThrowableMixin {
    
        @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "$id")
        private Throwable cause;
    }
    
    abstract class StackTraceElementMixin {
    
        @JsonProperty("className")
        private String declaringClass;
    
    }
    
    
    

    I'm manipulating the BeanDeserializerFactory to make buildThrowableDeserializer not treat Throwable any special but just like any other Object. Then using Mixins to define the "special" handling of Throwable and StackTraceElement to my liking.

    提交回复
    热议问题