JSON对象转换泛型问题
Posted 教主陈
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JSON对象转换泛型问题相关的知识,希望对你有一定的参考价值。
public class AppResult<T> {
private int code;
private Map<String,Object> data = new HashMap<String,Object>();
private int success;
private int ret;
private String msg;
public enum status {
SUCESS(1),
FAIL(0),
EXCEPTION(-1);
status(int value) {
this.value = value;
}
private int value;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
public AppResult<T> setResult(String name,T data){
this.data.put(name,data);
return this;
}
public AppResult<T> success(String dataName,T data){
this.setSuccess(status.SUCESS.getValue());
this.data.put(dataName,data);
this.setRet(200);
this.setCode(0);
return this;
}
public AppResult<T> fail(String msg) {
this.setSuccess(status.FAIL.getValue());
this.setMsg(msg);
this.setRet(200);
this.setCode(-1);
return this;
}
public AppResult<T> exception(Throwable e) {
this.setSuccess(status.EXCEPTION.getValue());
this.setMsg(e.getMessage());
this.setRet(200);
this.setCode(-1);
return this;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getSuccess() {
return success;
}
public void setSuccess(int success) {
this.success = success;
}
public int getRet() {
return ret;
}
public void setRet(int ret) {
this.ret = ret;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}
//如下将一个json字符串转成AppResult对象后,转成CrmShopCustVO会报错
AppResult<CrmShopCustVO> appResult = JsonUtil.jsonToObject((String) result, new TypeReference<AppResult<CrmShopCustVO>>() {});
Map<String, Object> dataMap = appResult.getData();
//下面这句话会报错: LikedHashMap can not convert to CrmShopCustVO
CrmShopCustVO crmShopCustomerVo = (CrmShopCustVO)dataMap.get("result");
因为private Map<String,Object> data是Object类型,默认转成了LinkedhashMap,应该讲data改为 private Map<String,T> data,如下显示:
public class AppResult<T> {
private int code;
private Map<String,T> data = new HashMap();
private int success;
private int ret;
private String msg;
以上是关于JSON对象转换泛型问题的主要内容,如果未能解决你的问题,请参考以下文章
JSON_常用类JSON与对象的互相转换TypeReference泛型遇到的坑
JSON_常用类JSON与对象的互相转换TypeReference泛型遇到的坑