Jackson JSON对象映射器反序列化为LinkedHashMap而不是HashMap

时间:2016-12-23 17:49:33

标签: java json serialization jackson

我有一张有内部地图的POJO。我希望从我的JSON反序列化为HashMap,但Jackson将内部映射从JSON反序列化为LinkedHashMap。我可以通过将Map的类型从“Map”更改为“HashMap”来强制它使用HashMap,但我想知道是否有办法告诉Jackson反序列化为Map的特定实现?

这是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
        }]
    }
}

转化课程:

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;
    }
}

我如何使用ObjectMapper:

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

1 个答案:

答案 0 :(得分:0)

如果你想要其他类型,你可以实现Jackson转换器并用它注释你的课程。

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
}