Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson- JsonSerializable- when should we implement serializeWithType method

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.

like image 910
Johnny P Avatar asked Nov 13 '13 06:11

Johnny P


1 Answers

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).

like image 182
StaxMan Avatar answered Oct 29 '22 13:10

StaxMan