问题 如果getters抛出异常,如何让Jackson忽略属性


我有很多来自供应商的类,他们喜欢在属性访问上随机抛出RuntimeExceptions。

public Object getSomeProperty() {
    if (!someObscureStateCheck()) {
        throw new IllegalStateExcepion();
    }
    return calculateTheValueOfProperty(someRandomState);
}

我无法更改类,无法添加注释,为每个类定义mixins是不现实的,因为堆栈的这一部分经常变化。

如果杰克逊的getter抛出异常,我如何让杰克逊忽略一个属性?


12924
2018-02-12 09:51


起源

是否可以使用try catch? - Joshua H
我会调查使用自定义设置对象映射器 JsonGenerator,可能通过扩展和修改 默认实现 以不同方式忽略/处理异常。 - Vulcan


答案:


去表演 自定义序列化 在杰克逊,你可以 注册一个模块 用一个 BeanSerializerModifier 它指定了所需的任何修改。在你的情况下, BeanPropertyWriter.serializeAsField 是负责序列化单个字段的方法,所以你应该自己创建 BeanPropertyWriter 忽略字段序列化的异常,并使用a注册模块 BeanSerializerModifier 用的 changeProperties 替换所有默认值 BeanPropertyWriter 具有您自己实现的实例。以下示例演示:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.*;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

public class JacksonIgnorePropertySerializationExceptions {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new SimpleModule().setSerializerModifier(new BeanSerializerModifier() {
            @Override
            public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
                return beanProperties.stream().map(bpw -> new BeanPropertyWriter(bpw) {
                    @Override
                    public void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception {
                        try {
                            super.serializeAsField(bean, gen, prov);
                        } catch (Exception e) {
                            System.out.println(String.format("ignoring %s for field '%s' of %s instance", e.getClass().getName(), this.getName(), bean.getClass().getName()));
                        }
                    }
                }).collect(Collectors.toList());
            }
        }));

        mapper.writeValue(System.out, new VendorClass());
    }

    public static class VendorClass {
        public String getNormalProperty() {
            return "this is a normal getter";
        }

        public Object getProblematicProperty() {
            throw new IllegalStateException("this getter throws an exception");
        }

        public String getAnotherNormalProperty() {
            return "this is a another normal getter";
        }
    }
}

上面的代码使用Jackson 2.7.1和Java 1.8输出以下代码:

ignoring java.lang.reflect.InvocationTargetException for field 'problematicProperty' of JacksonIgnorePropertySerializationExceptions$VendorClass instance
{"normalProperty":"this is a normal getter","anotherNormalProperty":"this is a another normal getter"}

显示出来 getProblematicProperty,抛出一个 IllegalStateException,将从序列化值中省略。


12
2018-02-15 18:38