'Using MultiValuedMap with Jackson

Hello I am trying to create an object from the following json :

    {
    "property1": "value1",
    "property2": [
        {"key1":"value1"},
        {"key1":"value2"},
        {"key2":"value1"}
    ]
}

The reason am using MultiValuedMap is because the keys in property 2 can be duplicates (as for the values).

The problem is that jackson throws an error when I try something like this :

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@EqualsAndHashCode
@JsonInclude(JsonInclude.Include.NON_NULL)
public class MyClass {
    
    private String property1;

    private List<MultiValuedMap<String, String>> property2;

}

As for the controller it's like this :

@PostMapping(value = "update")
MyClass saveMyClass(@RequestBody @Valid MyClass myClass);

but when trying to send the json to my api it gives the following error :

org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.apache.commons.collections4.MultiValuedMap]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of org.apache.commons.collections4.MultiValuedMap (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information



Solution 1:[1]

Why not just use a List<Map.Entry<String,String>> ?

This works right out of the box and if you really want to use a MuliValuedMap you can convert the List into one with the following sniped:

var map = new ArrayListValuedHashMap<String, String>();
result.property2.stream()
                        .collect(Collectors.groupingBy(Map.Entry::getKey))
                        .entrySet()
                        .forEach(entry ->
                                         map.putAll(entry.getKey(),
                                                    entry.getValue().stream().map(Map.Entry::getValue).toList()));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 3Fish