Jackson- JsonSerializable-我们什么时候应该实现serializeWithType方法

Joh*_*y P 5 serialization json jackson

我正在使用JsonSerializable接口来自定义我的JSON输出。我可以通过覆盖“ serialize”方法来自定义JSON序列化。但是我想知道还需要实现“ serializeWithType”方法的情况。我找不到使用此方法的任何示例。有人可以通过示例帮助我理解此方法的需求吗?提前致谢。

Sta*_*Man 6

serializeWithType()如果类型的实例需要支持多态类型处理(直接,当类型具有时@JsonTypeInfo;或者当启用“默认类型”时),则需要它。

典型的实现取决于您输出的 JSON 结构类型;如果值被序列化为简单的标量(如 JSON 字符串),您将使用以下内容:

// V here is whatever type 'this' is
@Override
public void serializeWithType(JsonGenerator jgen, SerializerProvider provider,
        TypeSerializer typeSer)
    throws IOException, JsonGenerationException
{
    typeSer.writeTypePrefixForScalar(this, jgen, V.class);
    serialize(value, jgen, provider);
    typeSer.writeTypeSuffixForScalar(this, jgen);
}
Run Code Online (Sandbox Code Playgroud)

而之所以需要这样的方法,只是因为TypeSerializer不知道本身会有什么样的JSON表示值;并且因为该表示决定了Type Id将如何包含(例如,只有 JSON 对象具有命名属性)。