gpt4 book ai didi

java - 如果 getter 抛出异常,如何让 Jackson 忽略属性

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:14 26 4
gpt4 key购买 nike

我有大量来自供应商的类,它们喜欢在属性访问时随机抛出 RuntimeExceptions。

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

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

如果某个属性的 getter 抛出异常,我如何让 Jackson 忽略该属性?

最佳答案

执行custom serialization在 jackson ,你可以register a moduleBeanSerializerModifier指定需要进行的任何修改。在你的情况下,BeanPropertyWriter.serializeAsField是负责序列化各个字段的方法,因此您应该创建自己的 BeanPropertyWriter 来忽略字段序列化的异常,并使用使用 changePropertiesBeanSerializerModifier 注册一个模块。用您自己的实现替换所有默认的 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,将从序列化值中省略。

关于java - 如果 getter 抛出异常,如何让 Jackson 忽略属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35359430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com