比如我httpclient调用的接口返回的格式是这样的:
一:data里是个对象
{ "code": 200, "message": "执行成功", "data": { "userId": 1, "userName": "Jamie", "roles": "admin", "realName": "测试人员", "tel": "13651046002", "email": "12345@qq.com", "enabled": true } }
1.添加pom依赖
<!--集成lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 集成json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
2.定义一个返回报文实体
/** * @author: sujing * @version: 1.0.0 * @ClassName: Return.java * @date: 2019/10/11 16:24 * 返回报文封装 */ @Data public class Return<T> { String code; String message; T data; public Return() { } public Return(String code, String message) { this.code = code; this.message = message; } public Return(String code, String message, T data) { this.code = code; this.message = message; this.data = data; } }
3.解析httpclient返回的参数
//httpClient调用接口,返回String字符串 String httpClientReturn = HttpClientUtil.get("http://xxxxx:9099/jwtauthsvr/api/getUserInfoByName", request.getHeader("Authorization")); //转成JsonObject JSONObject UserInfoReturn = JSON.parseObject(httpClientReturn); //转成自定义Return报文对象 Return returnMsg = JSON.toJavaObject(UserInfoReturn, Return.class); //获取报文里data参数 String JSONData = JSON.toJSONString(returnMsg.getData()); //转成UserInfo对象 UserInfo userInfo = JSON.parseObject(JSONData, UserInfo.class);
二:data里是个集合
{ "code": 200, "message": "success", "data": { "total": 16, "list": [ { "userId": 1, "userName": "Jamie", "roles": "admin", "realName": "测试人员", "tel": "13651046002", "email": "12345@qq.com", "idCard": "1111111111", "enabled": true, "relType": 0, "relId": 111098, "password": "xxx", "registrationTime": "2019-08-04 20:35:44", "updateTime": "2019-08-04 20:35:44" }, { "userId": 2, "userName": "Bruce", "roles": "admin", "realName": "测试人员2", "tel": "13651046888", "email": "wwee@qq.com", "idCard": "370214199555555555", "enabled": true, "relType": 0, "relId": 111099, "password": "xxx", "registrationTime": "2019-08-04 20:50:15", "updateTime": "2019-08-04 20:50:15" } ], "pageNum": 1, "pageSize": 25, "size": 16, "startRow": 1, "endRow": 16, "pages": 1, "prePage": 0, "nextPage": 0, "isFirstPage": true, "isLastPage": true, "hasPreviousPage": false, "hasNextPage": false, "navigatePages": 8, "navigatepageNums": [ 1 ], "navigateFirstPage": 1, "navigateLastPage": 1, "firstPage": 1, "lastPage": 1 } }
1.解析httpclient返回的参数
//httpClient调用接口,返回String字符串 String httpClientReturn = HttpClientUtil.get("http://xxxxx:9099/jwtauthsvr/api/getUserInfoByName", request.getHeader("Authorization"));
//转成JsonObject JSONObject UserInfoReturn = JSON.parseObject(httpClientReturn); //获取返回报文格式 Return returnMsg = JSON.toJavaObject(UserInfoReturn, Return.class); //获取报文里data参数 String JSONData = JSON.toJSONString(returnMsg.getData()); //获取data里的list List<UserInfo> userInfoList = JSON.parseObject(JSONData, new TypeReference<List<UserInfo>>() {});