Skip to content Skip to sidebar Skip to footer

Convert Json Response Into List

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': '0

Solution 1:

JSONObject data = newJSONObject(response);
JSONArray accounts = data.getJSONArray("data");    
List<Account> accountList = newGson().fromJson(accounts.toString(), newTypeToken<ArrayList<Account>>(){}.getType());

If you cannot change your JSON response to remove the inner "data" key, you can use this:

Gsongson=newGson();
ArrayList<Account> accountList = newArrayList<Account>();
JSONArrayaccounts= data.getJSONArray("data");  
for (inti=0; i < accounts.length(); i++) {
  JSONObjecta= accounts.getJSONObject(i).getJSONObject("data");
  accountList.add(gson.fromJson(a.toString(), Account.class));
}

Solution 2:

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  }

Solution 3:

That nested "data" key is pointless. If you can fix your JSON you should make this instead.

{"data":[{"ac_id":"000","user_id":"000","title":"AAA"},{"ac_id":"000","user_id":"000","title":"AAA"}]}

And then this will work.

JSONObject data = newJSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = newGson()
    .fromJson(accounts.toString(), newTypeToken<ArrayList<Account>>(){}.getType());

Or, again, that first "data" isn't really necessary either. If you can get your JSON just to be the list of Accounts...

[{"ac_id":"000","user_id":"000","title":"AAA"},{"ac_id":"000","user_id":"000","title":"AAA"}]

This will work

List<Account> accountList = new Gson()
    .fromJson(response, new TypeToken<ArrayList<Account>>(){}.getType());

Solution 4:

if you have access to where the JSON was created, i think you should make it like this:

{"data":[{"ac_id":"000","user_id":"000","title":"AAA"},{"ac_id":"000","user_id":"000","title":"AAA"}]}

then to convert it, just use this code: (where jsonString is the string above)

List<Account> accountList = new Gson().fromJson(jsonString, new TypeToken<ArrayList<Account>>(){}.getType());

Post a Comment for "Convert Json Response Into List"