Search code examples
javajsonjacksonjson-deserialization

How can I get Jackson to deserialize into my own Array implementation


Given my own array implementation MyArray<T>, how can I make it known to Jackson, so that it is able to deserialize from a JSON Array into MyArray<T>? So far I am only getting this exception:

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of MyArray out of START_ARRAY token

Solution

  • As Dariusz mentioned, it's good to take advantage of the fact that Array class has constructor accepting normal array.

    Look, if you use default serializer - your array serialized to JSON would look like:

    {"items":["item1","item2"],"size":2,"ordered":true}
    

    it's clearly a waste of space, unless you want size and ordered fields to be preserved.

    I suggest you changing the way you serialize your object so that it would look more like normal array, on the other end - deserialization can build Array object again.

    If you add following pair of serializer and deserializer:

    SimpleModule module = new SimpleModule();
    module.addDeserializer(Array.class, new StdDelegatingDeserializer<>(
        new StdConverter<Object[], Array>() {
            @Override
            public Array convert(Object[] value) {
                return new Array(value);
            }
    }));
    
    module.addSerializer(Array.class, new StdDelegatingSerializer(
        new StdConverter<Array, Object>() {
            @Override
            public Object convert(Array value) {
                return value.toArray();
            }
    }));
    
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    

    you will have transparent conversion between these types