gpt4 book ai didi

Android Json 解析与 Gson

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:39 24 4
gpt4 key购买 nike

我正在尝试使用 Gson 将 json 数据从 URL 映射到我的 java 类。这是该类的代码:

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 可能会解决这个问题”

我该如何解决这个问题并将 Gson 作为 ArrayList 返回?

最佳答案

将构造函数添加到您的 Sessions 类:

public class Sessions {
public Boolean active;
public String contributor_covu_id;
public String created_at;
public String key;
public String status;

void Sessions()
{
}
.
.
.
}

关于Android Json 解析与 Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6371764/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com