我是 GSON 的新手。我需要将以下 JSON 响应转换为列表。
JSON 响应:
{
"data": [{
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}, {
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}]
}
我有一个类来转换数据
帐户。爪哇
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+'}';
}
}
当我在课堂上做出回应时,我得到:
[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 响应以删除内部“data”键,您可以使用以下命令:
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));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)