Raw JSON Serialization and Deserialization

Last modified: 22/08/2020

The following allows to serialize JSON to a string:

public class RawJsonDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        JsonNode node = p.getCodec().readTree(p);
        return node.toString();
    }
}

And deserialize back from string to JSON:

public class RawJsonSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeRawValue(value);
    }
}

The usage looks like this:

@JsonSerialize(using = RawJsonSerializer.class)

or respectively:

@JsonDeserialize(using = RawJsonDeserializer.class)