Seephor
Seephor

Reputation: 1732

Jackson JSON object mapper deserializes to LinkedHashMap instead of HashMap

I have a POJO that has an inner map. I want this to deserialize into a HashMap from my JSON, but Jackson deserializes the inner map from the JSON into a LinkedHashMap. I can force it to use HashMap by changing the type of the Map from "Map" to "HashMap", but I want to know if there is a way to tell Jackson to deserialize into a specific implementation of Map?

Here is the JSON:

{
    "transforms": {
        "variable_name1": [{
            "min": 100,
            "max": 200,
            "value": 0.6
        }],
        "variable_name2": [{
            "min": 100,
            "max": 200,
            "value": 0.6
        }],
        "variable_name3": [{
            "min": 100,
            "max": 200,
            "value": 0.6
        }]
    }
}

And the Transforms class:

public class Transformer {
    Map<String, List<Transform>> transforms;

    public Transformer() {
        transforms = new HashMap<String, List<Transform>>();
    }

    public void setTransforms(Map<String, List<Transform>> transforms) {
        this.transforms = transforms;
    }
}

How I am using the ObjectMapper:

try(Reader reader = new InputStreamReader(TransformTester.class.getResourceAsStream("transforms.json"), "UTF-8")) {
            ObjectMapper objMapper = new ObjectMapper();
            Transformer tr = objMapper.readValue(reader, Transformer.class);
}

Upvotes: 10

Views: 15471

Answers (1)

Jan Cetkovsky
Jan Cetkovsky

Reputation: 776

If you want some other type, you can implement the Jackson converter and annotate your class with it.

public static class TransformConverter implements Converter<Map<String,List>,Map<String,List>>{

    @Override
    public Map<String,List> convert(Map<String,List> map) {
        return new HashMap<>(map);
    }

    @Override
    public JavaType getInputType(TypeFactory typeFactory) {
        return typeFactory.constructMapType(Map.class, String.class, List.class);
    }

    @Override
    public JavaType getOutputType(TypeFactory typeFactory) {
        return typeFactory.constructMapType(Map.class, String.class, List.class);
    }
}



public static class Transformer {
    @JsonDeserialize(converter = TransformConverter.class)
    Map<String, List<Transform>> transforms;
//rest of your class
}

Upvotes: 3

Related Questions