我想將使用Gson的json數據從URL映射到我的java類。這是類代碼:Android Json使用Gson解析
public class Sessions {
public Boolean active;
public String contributor_covu_id;
public String created_at;
public String key;
public String status;
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getContributor_covu_id() {
return contributor_covu_id;
}
public void setContributor_covu_id(String contributor_covu_id) {
this.contributor_covu_id = contributor_covu_id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String type;
}
,這是調用服務和地圖JSON
public static List<Sessions> getSessions(String urlString)
throws IOException {
Sessions[] sessions;
List<Sessions> tempList = null;
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
StringBuilder sb = new StringBuilder();
String line;
// Response response = null;
JSONObject j = null;
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
conn.disconnect();
try {
j = new JSONObject(sb.toString());
sessions = gson.fromJson(j.toString(), Sessions[].class);
tempList = Arrays.asList(sessions);
// response = gson.fromJson(j.toString(), Response.class);
// tempList.add(response);
} catch (JSONException e) {
e.printStackTrace();
}
return tempList;
}
雖然代碼是正確的,我得到的類的代碼一個Gson異常「無法爲類com.test.Sessions調用無參數構造函數;使用Gson爲此類型註冊一個InstanceCreator可能會解決此問題」
如何解決此問題d將Gson作爲ArrayList返回?
正如邊評論,代碼讀取JSON至少有一個錯誤(不指定輸入編碼),並且由於逐行讀取內容(應將輸入源直接傳遞給JSON解析庫)效率相當低。最後,需要創建中間的JSONObject,而不是直接的數據綁定內容(GSON可以完成)。 – StaxMan 2011-06-20 03:45:29