Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON response into List<T>

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?

like image 381
user3478224 Avatar asked Jan 05 '23 21:01

user3478224


2 Answers

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));
}
like image 149
Elias N Avatar answered Jan 07 '23 10:01

Elias N


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  }
like image 23
MezzDroid Avatar answered Jan 07 '23 12:01

MezzDroid