簡體   English   中英

如果getters拋出異常,如何讓Jackson忽略屬性

[英]How to make Jackson ignore properties if the getters throw exceptions

我有很多類來自供應商,他們喜歡在屬性訪問上隨機拋出RuntimeExceptions。

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

我無法更改類,無法添加注釋,為每個類定義mixins是不現實的,因為堆棧的這一部分經常變化。

如果傑克遜的getter拋出異常,我如何讓傑克遜忽略一個屬性?

要在Jackson中執行自定義序列化 ,您可以使用BeanSerializerModifier 注冊模塊 ,該模塊指定所需的任何修改。 在您的情況下, BeanPropertyWriter.serializeAsField是負責序列化單個字段的方法,因此您應該創建自己的BeanPropertyWriter ,忽略字段序列化的異常,並使用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"}

顯示拋出IllegalStateException getProblematicProperty將從序列化值中省略。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM