Java TypeWrappedDeserializer-class And Method Code Example


Here is an example of how to use the TypeWrappedDeserializer class from the com.fasterxml.jackson.databind package in the Jackson library for Java:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.deser.std.TypeWrappedDeserializer;

import java.io.IOException;

public class Example {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new MyModule());

        String json = "{\"value\":\"Hello\"}";
        MyObject object = mapper.readValue(json, MyObject.class);
        System.out.println(object.toString());
    }

    static class MyObject {
        private String value;

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "MyObject{" +
                    "value='" + value + ''' +
                    '}';
        }
    }

    static class MyModule extends com.fasterxml.jackson.databind.module.SimpleModule {
        public MyModule() {
            super();
            addDeserializer(String.class, new MyDeserializer());
        }
    }

    static class MyDeserializer extends StdDeserializer<String> {
        public MyDeserializer() {
            super(String.class);
        }

        @Override
        public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            String value = (String) super.deserialize(p, ctxt);
            return value.toUpperCase();
        }
    }
}

This code creates an instance of the ObjectMapper class, and register a custom deserializer for String objects that converts the value to uppercase. Then it deserializes a json string to MyObject class and prints the resulting object to the console.

The output of this code would be:

MyObject{value='HELLO'}

The TypeWrappedDeserializer class is used to wrap a JsonDeserializer in order to make it work for a specific type. In this example, MyDeserializer is a custom deserializer that extends StdDeserializer and converts the value to uppercase.

It wrapped by TypeWrappedDeserializer to make it work only for String type. And it is registered to the ObjectMapper using MyModule class.