参考过的资料:
案例的介绍:
userAuth = null
,案例后userAuth
结果如下:{ "flag": true, "code": 20000, "message": "操作成功", "data": { "id": 1, "userId": 1, "categoryId": null, "articleCover": null, "articleTitle": "人工标题1", "articleContent": "人工内容", "type": 1, "originalUrl": null, "isTop": 0, "isDelete": 0, "status": 1, "createTime": "2022-04-12T16:55:22", "updateTime": null, "userAuth": { "id": 1, "userInfoId": 1, "username": "shisan@163.com", "password": "$2a$10$jVUy2pE0JcEnx/owx1LZwe9A0y4ZWIcX3ZsieLFUvoLgP9JaJRAnu", "loginType": 1, "ipAddress": "127.0.0.1", "ipSource": "", "createTime": "2021-08-12T15:43:18", "updateTime": "2022-04-11T23:42:55", "lastLoginTime": "2022-04-11T23:42:55" } } }
package com.cduy.blog.service.impl; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.cduy.blog.dao.ArticleDao; import com.cduy.blog.domain.Article; import com.cduy.blog.domain.UserAuth; import com.cduy.blog.service.ArticleService; import com.cduy.blog.vo.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; /** * @author CDUY * @version 1.0 */ @Service public class ArticleServiceImpl extends ServiceImpl<ArticleDao, Article> implements ArticleService { @Autowired private ArticleService articleService; @Autowired private RestTemplate restTemplate; public Article queryArticleById(Integer articleId) { //1.查询文章 Article article = articleService.getById(articleId); //2.远程查询user //2.1url地址 String url = "http://localhost:81/users/" + article.getUserId(); //2.2发起调用 因为返回结果被封装成了 Result Result<UserAuth> result = restTemplate.getForObject(url, Result.class); // 因为返回的数据是 Result 需要处理数据 String jsonObject = JSON.toJSONString(result.getData()); UserAuth userAuth = JSON.parseObject(jsonObject, UserAuth.class); //3.存入article article.setUserAuth(userAuth); //4.返回 return article; } }
article.setUserAuth(userAuth);
,但这里需要对Json处理java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.cduy.blog.domain.UserAuth
,该错误是发生在用article.setUserAuth(userAuth);
,因为在数据返回时将结果统一封装成Result
类,所以不可以简单将Result.getData
便取出该用户数据了,而是应该先转成json
对象再转换成java
对象。22年4月13日第一次提交的分支