代码之家  ›  专栏  ›  技术社区  ›  Hasan Can Saral

com。fasterxml。杰克逊。数据绑定。JsonSerializer按键排除字段

  •  1
  • Hasan Can Saral  · 技术社区  · 8 年前

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

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

    所以这个类还没有完全 Serializable ,我遇到了 StackOverflowError 当我尝试使用Spring Boot将其序列化为json时 @ResponseBody

    我有两种控制器方法:

    @ResponseBody public SomeClassImpl get();
    
    @ResponseBody public SomeOtherClass find();
    

    我可以控制 SomeOtherClass 其中包括 SomeClass 作为财产。

    我不知道如何使用忽略字段 @JsonIgnore 注释,我可能需要控制源代码。我可以对注释所做的是可以忽略 SomeClass类 属性来自 其他类别 这对上面的第一种方法没有帮助。所以我决定实施 JsonSerializer<SomeClassImpl> :

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

    或者我可以用注释来处理这个问题吗?如果是,如何?谢谢

    1 回复  |  直到 8 年前
        1
  •  3
  •   cassiomolin    8 年前

    如果不能修改源代码,可以使用 混合注释 添加 Jackson annotations 给豆子。

    首先在注释接口或类中定义混合:

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

    然后配置 ObjectMapper 要将定义的接口用作POJO的混合接口,请执行以下操作:

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

    • 全部的 annotation sets 杰克逊认识到的可以混入其中。
    • 可以混合使用各种注释(成员方法、静态方法、字段、构造函数注释)。
    • 只有方法(和字段)名称和签名用于匹配注释:访问定义( private ,则, protected ,…)和方法实现被忽略。

    有关更多详细信息,请查看Jackson documentation