把Object类转换为实体类

rap

问题描述

在用SpringBoot写controller的时候,需要接受一个map的Object,之后要把Object转为特定的类,代码如下:

public boolean postArticle(@RequestBody Map<String, Object> map) {
        ArticleInfo articleInfo = (ArticleInfo) map.get("articleInfo");
        ArticleContent articleContent = (ArticleContent) map.get("articleContent");
        System.out.println(articleInfo + " " + articleContent);
        return true;
}

之后爆出异常:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class 
cn.zi10ng.blog.domain.ArticleInfo (java.util.LinkedHashMap is in module java.base of loader
 'bootstrap'; cn.zi10ng.blog.domain.ArticleInfo is in unnamed module of loader 
 org.springframework.boot.devtools.restart.classloader.RestartClassLoader @19b54dc3)

问题原因

map中取出的是Object,不能直接把Object转为特定的实体类

解决办法

需要通过json来作为中间介质:

   public boolean postArticle(@RequestBody Map<String, Object> map) throws IOException {

        ObjectMapper objectMapper = new ObjectMapper();
        String jsonInfo = objectMapper.writeValueAsString(map.get("articleInfo"));
        String jsonContent = objectMapper.writeValueAsString(map.get("articleContent"));
        ArticleInfo articleInfo = objectMapper.readValue(jsonInfo,ArticleInfo.class);
        ArticleContent articleContent = objectMapper.readValue(jsonContent,ArticleContent.class);

        System.out.println(articleContent + " " +articleInfo);
        return articleService.insertArticle(articleInfo,articleContent);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值