如何防止 Jackson 序列化多态类型的注释属性? [英] How can I prevent Jackson from serializing a polymorphic type's annotation property?

查看:33
本文介绍了如何防止 Jackson 序列化多态类型的注释属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多态类型和从 JSON 反序列化到 POJO 的工作.事实上,我遵循了这里的文档.将 POJO 序列化为 JSON 时,我得到了一个不需要的属性,特别是逻辑类型名称.

I have polymorphic types and deserializing from JSON to POJO works. I followed the documentation here, in fact. When serializing POJOs into JSON I'm getting an unwanted attribute, specifically the logical type name.

import static org.codehaus.jackson.annotate.JsonTypeInfo.*;

@JsonTypeInfo(use=Id.NAME, include=As.PROPERTY, property="type")
@JsonSubTypes({
    @JsonSubTypes.Type(value=Dog.class, name="dog"),
    @JsonSubTypes.Type(value=Cat.class, name="cat")
})    
public class Animal { ... }

public class Dog extends Animal { ... }
public class Cat extends Animal { ... }

当 Jackson 序列化为 JSON 时,它提供了我不想公开的类型信息.

When Jackson serializes into JSON it provides the type information which I don't want to expose.

{"type":"dog", ... }
{"type":"cat", ... }

我能以某种方式阻止这种情况吗?我只想在反序列化时忽略 type.

Can I prevent this somehow? I only want to ignore type when deserializing.

推荐答案

一个简单的解决方案是将 @JsonTypeInfo@JsonSubTypes 配置移动到 >MixIn,然后只注册MixIn进行反序列化.

A simple solution would be to just move the @JsonTypeInfo and @JsonSubTypes configs to a MixIn, and then only register the MixIn for deserialization.

mapper.getDeserializationConfig().addMixInAnnotations(MyClass.class, MyMixIn.class)

这篇关于如何防止 Jackson 序列化多态类型的注释属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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