I am new to GSON. I need to convert the following JSON response into a List.
JSON response:
{
"data": [{
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}, {
"data": {
"ac_id": "000",
"user_id": "000",
"title": "AAA"
}
}]
}
I have a class to cast data
Account. 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+'}';
}
}
When I cast the response with my class I get:
[Account{ac_id="000", user_id="000", title="AAA"}, Account{ac_id="000", user_id="000", title="AAA"}]
Now I need to put these two values into a List<Account>
.
What do you suggest?
JSONObject data = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = new Gson().fromJson(accounts.toString(), new TypeToken<ArrayList<Account>>(){}.getType());
If you cannot change your JSON response to remove the inner "data" key, you can use this:
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));
}
For that you can use Tokens so that gson can understand the custom type...
TypeToken<List<Account>> token = new TypeToken<List<Account>>(){};
List<Account > accountList= gson.fromJson(response, token.getType());
for(Account account : accountList) {
//some code here for looping }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With