1.restTemplate调用的两种方式及获取字符串转换对象model的处理,统一按接收字符串,然后gson转换为对象的方式。
ResponseData对象包含的属性
private String resCode;
private String resMsg;
private T data;
import java.lang.reflect.Type;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
@Test public void testPost1() { String url = "http://IP:PORT/"; String memNo = "111"; ReqVO reqVo = new ReqVO(); reqVo.setMemNo(memNo); String json = restTemplate.postForObject(url, reqVo, String.class); log.info("string = " + json); //java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xxx // ResponseData<OpenInfoStatusVO> responseEntity = new Gson().fromJson(json, ResponseData.class); //这个是关键 Type type = new TypeToken<ResponseData<MyResponseInfoStatusVO>>() {}.getType(); ResponseData<MyResponseInfoStatusVO> responseEntity = new Gson().fromJson(json, type); if (responseEntity == null || responseEntity.getData() == null) { log.info("postForEntity null,params memNo=[{}]",memNo); }else { MyResponseInfoStatusVOstatusVo = (MyResponseInfoStatusVO) responseEntity.getData(); log.info("postForEntity ok,result=[{}],params memNo=[{}]",GsonUtils.toJson(statusVo),memNo); } }
import java.lang.reflect.Type; import com.google.common.reflect.TypeToken; import com.google.gson.Gson; @Test public void testPost2() { String url = "http://IP:PORT/"; String memNo = "222"; ReqVO reqVo = new ReqVO(); reqVo.setMemNo(memNo); //区别点 ResponseEntity<String> response = restTemplate.postForEntity(url, reqVo, String.class); log.info("string = " + GsonUtils.toJson(response)); //java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to xxx // ResponseData<MyResponseInfoStatusVO> responseEntity = new Gson().fromJson(response.getBody(), ResponseData.class); //这个是关键 Type type = new TypeToken<ResponseData<MyResponseInfoStatusVO>>() {}.getType(); ResponseData<MyResponseInfoStatusVO> responseEntity = new Gson().fromJson(response.getBody(), type); if (responseEntity == null || responseEntity.getData() == null) { log.info("postForEntity null,params memNo=[{}]",memNo); }else { MyResponseInfoStatusVOstatusVo = (MyResponseInfoStatusVO) responseEntity.getData(); log.info("postForEntity ok,result=[{}],params memNo=[{}]",GsonUtils.toJson(statusVo),memNo); } }