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;

 
原文地址:https://www.cnblogs.com/chenge-0401/p/9844239.html