当前位置: 首页 > 知识库问答 >
问题:

JAVAClassCastException:类java。util。HashMap无法强制转换:SpringBoot

全昊焜
2023-03-14

我们正在从Spring 5.0迁移到Spring Boot 2.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的AbstractMessageConvertermetodProcessor.class抛出的

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

有人能提出解决这个问题的建议吗?

共有1个答案

隗和裕
2023-03-14

试试这个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.*反序列化。

 类似资料: