1. 程式人生 > >JSON對象轉換泛型問題

JSON對象轉換泛型問題

message pan 轉換 convert hash {} exc json對象 .get


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對象轉換泛型問題