【问题标题】:com.fasterxml.jackson.databind.JsonSerializer exclude fields by keycom.fasterxml.jackson.databind.JsonSerializer 按键排除字段
【发布时间】:2018-08-22 21:04:30
【问题描述】:

我有一个类,我无法控制它的来源:

public class SomeClassImpl implements SomeClass {
    private SomeField someFiled; // Not serializable
    ... // Some other fields that are serializable
}

所以这个类不完全是Serializable,当我尝试使用Spring Boot将它序列化为json时遇到StackOverflowError@ResponseBody

我有两个控制器方法:

@ResponseBody public SomeClassImpl get();

@ResponseBody public SomeOtherClass find();

我可以控制SomeOtherClass 的来源,其中包括SomeClass 作为属性。

我不知道如何使用@JsonIgnore 注释忽略字段,我可能需要控制源。我可以用注释做的是我可以忽略来自SomeOtherClassSomeClass 属性,这不会帮助上面的第一种方法。所以我决定实现JsonSerializer<SomeClassImpl>

@Override
public void serialize(SomeClassImpl someClass, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
    // I need to write all fields except some
}

或者我可以用注释来处理这个吗?如果是怎么办?谢谢。

【问题讨论】:

    标签: java spring-boot serialization jackson


    【解决方案1】:

    当无法修改源代码时,您可以使用mix-in annotationsJackson annotations 添加到bean。

    先定义一个混入注解接口或类:

    public interface FooMixIn {
    
        @JsonIgnore
        Object getBiz();
    }
    

    然后配置ObjectMapper 使用定义的接口作为你的POJO的混合:

    ObjectMapper mapper = new ObjectMapper().addMixIn(Foo.class, FooMixIn.class); 
    

    • Jackson 认识的所有annotation sets 都可以混入其中。
    • 可以混入各种注解(成员方法、静态方法、字段、构造函数注解)。
    • 只有方法(和字段)名称和签名用于匹配注释:访问定义(privateprotected、...)和方法实现被忽略。

    更多详情,请查看 Jackson documentation

    【讨论】:

    • 感谢您的回答。您是否阅读了我提到为什么我不能使用注释的部分,或者我遗漏了什么?
    • @HasanCanSaral 请再读一遍我的回答。 Mix-ins 允许您在不修改其源代码的情况下向 bean 添加注释。
    • 我想我错过了一些东西,我现在正在尝试一下。很快就会更新,感谢您的跟进,不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2015-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多