java.lang.classcastexception:无法强制转换类java.util.hashmap:springboot

vltsax25  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(1118)

我们正在进行从Spring5.0到SpringBoot2.4版本的迁移。我的控制器代码如下

@RequestMapping(value = "/getTreeNodesByFilter.action", method = RequestMethod.GET)
    public @ResponseBody Map<String, ? extends Object> getTreeNodesByFilter(@RequestParam("type") String type,
            @RequestParam("id") Long id, @RequestParam("pageNo") int pageNo, @RequestParam("pageSize") int pageSize,
            @RequestParam("filterBy") String filterBy) {
        Map<String, Object> responseMap = commonService.getTreeNodesByFilter(type, id, pageNo, pageSize, filterBy);
        return ResponseUtil.getMap(responseMap);
    }

响应主体是一个hashmap,如上图所示。这段代码在普通的spring webapp中运行良好。同样的代码当我们厌倦了springboot时,我们得到了以下错误

java.lang.ClassCastException: class java.util.HashMap cannot be cast to class com.scriptless.web.security.exceptions.JsonError (java.util.HashMap is in module java.base of loader 'bootstrap'; com.scriptless.web.security.exceptions.JsonError is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader @5f00ac7a)

此错误是在执行代码时从spring-webmvc.jar的abstractmessageconvertermethodprocessor.class引发的

((HttpMessageConverter) converter).write(body, selectedMediaType, outputMessage);

有人能建议一下要怎么解决这个问题吗?

7rfyedvj

7rfyedvj1#

试试这个objectmapper,

public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
                .configure(MapperFeature.USE_GETTERS_AS_SETTERS, false);
        SimpleModule module = new SimpleModule();

        objectMapper.registerModule(module);
        objectMapper.registerModule(new JavaTimeModule());
        PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator.builder()
            .allowIfSubType("java.util.") //$NON-NLS-1$
                .build();

        objectMapper.setPolymorphicTypeValidator(ptv);
        objectMapper.activateDefaultTyping(ptv, DefaultTyping.NON_FINAL);
        return objectMapper;
    }

这将允许包java.util.*的所有子类型进行反序列化。

相关问题