如果getter抛出异常,如何使Jackson忽略属性 [英] How to make Jackson ignore properties if the getters throw exceptions

查看:157
本文介绍了如果getter抛出异常,如何使Jackson忽略属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有许多来自供应商的类,它们喜欢在属性访问中随机抛出RuntimeExceptions.

I have a multitude of classes coming from a vendor that like to randomly throw RuntimeExceptions on property access.

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

我不能更改类,不能添加注释,并且为每个单独的类定义mixin是不现实的,因为堆栈的这一部分经常更改.

I cannot change the classes, cannot add annotations and it's unrealistic to define mixins for every single class as this part of stack changes fairly often.

如果杰克逊的getter抛出异常,如何使它忽略该属性?

How do I make Jackson ignore a property if its getter throws an Exception?

推荐答案

要在Jackson中执行自定义序列化,您可以使用注册模块 /blob/jackson-databind-2.7.1/src/main/java/com/fasterxml/jackson/databind/ser/BeanSerializerModifier.java"rel =" noreferrer> BeanSerializerModifier ,用于指定需要进行的任何修改.在您的情况下, .java#L47"rel =" noreferrer> changeProperties ,用您自己的实现替换所有默认的BeanPropertyWriter实例.以下示例演示:

To perform custom serialization in Jackson, you can register a module with a BeanSerializerModifier that specifies whatever modifications are needed. In your case, BeanPropertyWriter.serializeAsField is the method responsible for serializing individual fields, so you should make your own BeanPropertyWriter that ignores exceptions on field serialization, and register a module with a BeanSerializerModifier that uses changeProperties to replace all default BeanPropertyWriter instances with your own implementation. The following example demonstrates:

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输出以下内容:

The above code outputs the following, using Jackson 2.7.1 and 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"}

表明抛出IllegalStateExceptiongetProblematicProperty将从序列化值中省略.

showing that getProblematicProperty, which throws an IllegalStateException, will be omitted from the serialized value.

这篇关于如果getter抛出异常,如何使Jackson忽略属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆