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);
}
To convert all the values of a LinkedHashMap to a List in Java, we can use the values() method. The values() is a method of the LinkedHashMap that returns a Collection of all the values in the map object. We can then convert this collection to a List object.
How to deserialize Date from JSON using Jackson. In order to correct deserialize a Date field, you need to do two things: 1) Create a custom deserializer by extending StdDeserializer<T> class and override its deserialize(JsonParser jsonparser, DeserializationContext context) method.
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With