我得到Json字符串,我想创建将Json字符串转换为Object的通用方法。 我创建了对象
public class ResponseMessage<T> {
private T result;
private ResultCode resultCode;
private String details;
public ResponseMessage(T result, ResultCode resultCode, String details) {
this.result = result;
this.resultCode = resultCode;
this.details = details;
}
public T getResult() {
return result;
}
public void setResult(T result) {
this.result = result;
}
public ResultCode getResultCode() {
return resultCode;
}
public void setResultCode(ResultCode resultCode) {
this.resultCode = resultCode;
}
public String getDetails() {
return details;
}
public void setDetails(String details) {
this.details = details;
}
}
我希望将泛型类型传递给我的类并返回对象。但我不知道怎么做。我创建了课程Converter
public class Converter {
private static Converter instance;
private Gson gson = new Gson();
public static Converter me() {
if (instance == null) {
instance = new Converter();
}
return instance;
}
public <T> T getModel(String jsonStr, Class<T> type) {
T t = gson.fromJson(jsonStr, type);
return t;
}
public <T> List<T> getModelList(String jsonStr, Class<T[]> clazz) {
T[] yourClassList = new Gson().fromJson(jsonStr, clazz);
return Arrays.asList(yourClassList);
}
}
我试过
String s = RESTUtil.doPost(url, formData);
ResponseMessage<ArrayList<CallDetail>> model = Converter.me().getModel(s, ResponseMessage<ArrayList<CallDetail>>.class);
但这是错的。 s
- 它是Json字符串。
ResponseMessage<ArrayList<CallDetail>>.class - type(I don't know how pass it)
答案 0 :(得分:0)
答案 1 :(得分:-1)
请参阅此处的文档:http://developer.android.com/reference/org/json/JSONObject.html
基本上你可以使用JSONObject类。它可以将字符串作为输入并转换为JSONObject的对象。
您可以使用此对象从JSON结构中获取单个元素(值)。