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> {

    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> {

    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {

The usage looks like this:

@JsonSerialize(using = RawJsonSerializer.class)

or respectively:

@JsonDeserialize(using = RawJsonDeserializer.class)