赞
踩
在使用RestTemplate.postForObject方法远程调用接口
返回的时候会自动转成LinkedHashMap,造成ClassCastException类型转换异常
- /**
- * post
- * @param url 请求地址
- * @param param 参数
- * @param returnClass 返回类型
- * @return
- */
- public <E> E postByDefault(String url, E param, Class<E> returnClass) {
- final HttpHeaders headers = new HttpHeaders();
- headers.setContentType(MediaType.APPLICATION_JSON);
- headers.set("Accept", "application/json");
- final HttpEntity<E> httpEntity = new HttpEntity<>(param, headers);
- return this.restTemplate.postForObject(url, httpEntity, returnClass);
- }
解决办法
第一种:
- JSONObject object = restTemplateClient.postByDefault(url,param, JSONObject.class);
- SysUserInfo[] userInfos = object.getObject("data",SysUserInfo[].class);
- List<SysUserInfo> userInfoList = Arrays.asList(userInfos);
第二种:
- ParameterizedTypeReference<List<SysUserInfo>> typeRef = new ParameterizedTypeReference<List<SysUserInfo>>() {};
- ResponseEntity<List<SysUserInfo>> responseEntity = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(param), typeRef);
- List<SysUserInfo> userinfoList= responseEntity.getBody();
以上就是本文的全部内容,希望对大家的学习有所帮助,欢迎评论交流。能get到知识点不要忘了关注点个赞~ 拒绝白嫖从我们做起hh~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。