首页 > 解决方案 > 使用 RestTemplae 获取 vavr Multimap 后的反序列化错误

问题描述

我正在尝试反序列化 Jackson Multimap

       //given
        val newUser = NewUserDTO(ALREADY_TAKEN_USERNAME, ALREADY_TAKEN_EMAIL,"qddqwdW221QZ&^$!")

        //when
        val response = restTemplate.exchange("http://localhost:${port}/user", HttpMethod.POST, HttpEntity(newUser), typeReference())

        //then
        Assertions.assertEquals(HttpStatus.UNPROCESSABLE_ENTITY, response.statusCode)

我得到一个例外:

Type definition error: [simple type, class io.vavr.collection.Multimap]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `io.vavr.collection.Multimap` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (PushbackInputStream); line: 1, column: 1]
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class io.vavr.collection.Multimap]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `io.vavr.collection.Multimap` (no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information
 at [Source: (PushbackInputStream); line: 1, column: 1]

有趣的是,如果我使用 String 来保存它的值并使用注入的 ObjectMapper,我可以反序列化响应我该怎么办?

标签: springkotlinresttemplatevavr

解决方案


好吧,那是我的错。我用过TestRestTemplate,就像文档描述的那样,我应该自己配置那个bean:

如果您需要自定义(例如添加其他消息转换器),请使用 RestTemplateBuilder @Bean。

我假设 RestTemplateBuilder 使用相同的 RestTemplate,因此如果为 RestTemplate 注册了一个模块,则应该为 RestTemplateBuilder 注册它


推荐阅读