vavr-jackson icon indicating copy to clipboard operation
vavr-jackson copied to clipboard

Nested maps are deserialized as java maps

Open heldev opened this issue 7 years ago • 6 comments

Hi, It looks like that it's impossible right now to deserialize a JSON as vavr map tree, because only top level elements are deserialized as javaslang collections, deeper levels are java containers:

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javaslang.collection.List;
import javaslang.collection.Map;
import javaslang.jackson.datatype.JavaslangModule;
import org.junit.Test;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;


public class VavrJacksonTest {

    private static final String JSON = "[\n" +
            "   {\n" +
            "        \"field1\": \"val1\",\n" +
            "        \"complexField\": {\n" +
            "            \"subField1\": \"subValue1\",\n" +
            "            \"subField2\": \"subValue2\"\n" +
            "        }\n" +
            "    }\n" +
            "]";


    @Test
    public void nested_maps_should_be_javaslang_maps() throws IOException {
        List<Map<String, Object>> listOfMapTrees = new ObjectMapper()
                .registerModule(new JavaslangModule())
                .readValue(JSON, new TypeReference<List<Map<String, Object>>>() {});

        assertThat(listOfMapTrees.get().apply("complexField")).isInstanceOf(Map.class);
        //Expecting:
        // <{"subField1"="subValue1", "subField2"="subValue2"}>
        //to be an instance of:
        // <javaslang.collection.Map>
        //but was instance of:
        // <java.util.LinkedHashMap>
    }
}

heldev avatar May 03 '17 20:05 heldev

This is expected behavior. By default, all JSON objects are deserialized to java.util.LinkedHashMap.

You can try using

new TypeReference<List<Map<String, Map<String,String>>>>() {}

instead of

new TypeReference<List<Map<String, Object>>>() {}

(unfortunately your example will fail because val1 is not a map)

ruslansennov avatar May 03 '17 20:05 ruslansennov

I understand that there is, probably, some technical limitation from the jackson side, but this issue automatically breaks #75 deserialize(serialize(o)) equals o rule and gives a really hard time in some cases. Would it be possible to fix it ?

heldev avatar May 03 '17 20:05 heldev

Would it be possible to fix it ?

Up to now I have no idea about how that issue should be fixed. Maybe tests will be produced without nested cases only...

ruslansennov avatar May 03 '17 20:05 ruslansennov

Hi @ruslansennov, do you have any updates on this? @heldev did you find a solution?

bduisenov avatar Feb 15 '18 13:02 bduisenov

@bduisenov, no, not really :-/

heldev avatar Feb 15 '18 23:02 heldev

You might find this Stackoverflow answer useful.

dbaltor avatar Feb 13 '21 03:02 dbaltor