我是 GSON 的新手。我需要将以下 JSON 响应转换为列表。
JSON 响应:
{
"data": [{
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}, {
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}]
}
我有一个类来转换数据
帐户。 Java
public class Account {
public int ac_id;
public int user_id;
public String title;
@Override
public String toString(){
return "Account{"+
"ac_id="+ac_id+
", user_id="+user_id+
", title="+title+'}';
}
}
当我将响应转换到我的类(class)时,我得到:
[Account{ac_id="000", user_id="000", title="AAA"}, Account{ac_id="000", user_id="000", title="AAA"}]
现在我需要将这两个值放入 List<Account>
中.
你有什么建议?
最佳答案
JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = new Gson().fromJson(accounts.toString(), new TypeToken<ArrayList<Account>>(){}.getType());
如果您无法更改 JSON 响应以删除内部“数据”键,您可以使用此方法:
Gson gson = new Gson();
ArrayList<Account> accountList = new ArrayList<Account>();
JSONArray accounts = data.getJSONArray("data");
for (int i = 0; i < accounts.length(); i++) {
JSONObject a = accounts.getJSONObject(i).getJSONObject("data");
accountList.add(gson.fromJson(a.toString(), Account.class));
}
关于java - 将 JSON 响应转换为 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41249123/