Search code examples
spring-web

Using MultiValuedMap as ResponseBody gives {"empty" : false} as response


I am trying to use MultiValuedMap as the ResponseBody of a rest service but the response I get in the browser is:

{"empty" : false}

This was working fine using MultiValueMap as the ResponseBody but after upgrading the org.apache.commons libraries, MultiValueMap is deprecated with instructions to use MultiValuedMap instead.

Here is relevant parts of my code:

import org.apache.commons.collections4.MultiValuedMap;

@RestController("DatabaseDefinitionRestController")
public class DatabaseDefinitionRestController {

    @RequestMapping(value = "/database/{id}/definitions", method = RequestMethod.GET)
    public MultiValuedMap<Long, DatabaseDefinition> mapDatabaseDefinitions(@PathVariable Long id) {
        return databaseDefinitionService.loadDatabaseDefinition(id);
    }
}

I also tried:

import org.apache.commons.collections4.multimap.ArrayListValuedHashMap;

@RestController("DatabaseDefinitionRestController")
public class DatabaseDefinitionRestController {

    @RequestMapping(value = "/database/{id}/definitions", method = RequestMethod.GET)
    public ArrayListValuedHashMap<Long, DatabaseDefinition> mapDatabaseDefinitions(@PathVariable Long id) {
        return databaseDefinitionService.loadDatabaseDefinition(id);
    }
}

Any help would be appreciated.


Solution

  • Whatever you're using for serialization probably has special case handling for all core Java collections, including Map. The deprecated MultiValueMap implements Map and thus benefits from that special handling. The new MultiValuedMap, for whatever reason, does not. This makes it fall back on default general handling, which depends on the internal implementation of whichever concrete class is used.

    Call asMap() on the MultiValuedMap to get a view of it that implements Map, and put that in your ResponseBody to get the special case Map-based serialization.