7

I am using JsonSerializable interface to customise my JSON output. I am able customise the JSON serialisation by overriding "serialize" method. But I wanted to know the scenarios where "serializeWithType" method is needed to be implemented as well. I could'nt find any examples where this method is being used. Can someone help me understand the need of this method with an example? Thanks in advance.

Johnny P
  • 73
  • 1
  • 4

1 Answers1

8

serializeWithType() is needed if instances of the type ever need to support polymorphic type handling (either direct, when type has @JsonTypeInfo; or when enabled with "default typing").

Typical implementation depends on what kind of JSON Structure you are outputting; if value is serialized as simple scalar (like JSON String), you'd use something like:

// 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);
}

and the reason why such a method is needed is simply because TypeSerializer does not know what kind of JSON representation value itself will have; and because that representation determines how Type Id will be included (for example, only JSON Objects have named properties).

bmargulies
  • 97,814
  • 39
  • 186
  • 310
StaxMan
  • 113,358
  • 34
  • 211
  • 239