Convert JSON response into List<T>

13,082

Solution 1

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));
}

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 = new JSONObject(response);
JSONArray accounts = data.getJSONArray("data");
List<Account> accountList = new Gson()
    .fromJson(accounts.toString(), new TypeToken<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());
Share:
13,082
user3478224
Author by

user3478224

Updated on June 19, 2022

Comments

  • user3478224
    user3478224 almost 2 years

    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?

  • OneCricketeer
    OneCricketeer over 7 years
    I'm not sure this will work with the nested "data" key
  • user3478224
    user3478224 over 7 years
    I get and JsonSyntaxException Expected BEGIN_ARRAY but was BEGIN_OBJECT
  • user3478224
    user3478224 over 7 years
    JsonSyntaxException Expected BEGIN_ARRAY but was BEGIN_OBJECT
  • user3478224
    user3478224 over 7 years
    JsonSyntaxException Expected BEGIN_ARRAY but was BEGIN_OBJECT
  • OneCricketeer
    OneCricketeer over 7 years
    Like I said - It's up to you to fix the actual JSON. Don't just copy the Java code I gave.
  • OneCricketeer
    OneCricketeer over 7 years
    Or you could not use Gson and parse the data yourself.
  • Elias N
    Elias N over 7 years
    @user3478224 As other users have mentioned, it's because you have a nested data key. You should have: { "ac_id": "000", "user_id": "000", "title": "AAA" } instead of { "data": { "ac_id": "000", "user_id": "000", "title": "AAA" } }
  • Elias N
    Elias N over 7 years
    @user3478224 see edit if you cannot change your JSON response
  • user3478224
    user3478224 over 7 years
    I appreciate your help but I can not modify my JSON string, it is working with my all classes with no problem. When I try to convert into an object array is when crashes.
  • user3478224
    user3478224 over 7 years
    How can I parse the data?
  • OneCricketeer
    OneCricketeer over 7 years
    Use the built-in JSONObject class and start parsing it. stackoverflow.com/questions/9605913/… Of course, you can do the same in Gson but using the otherwise named JsonObject
  • OneCricketeer
    OneCricketeer over 7 years
    You can't modify this one API response to not put "data": as part of the response?
  • user3478224
    user3478224 over 7 years
    I will try using String.replace to remove the parts that avoid match the form you suggest.
  • OneCricketeer
    OneCricketeer over 7 years
    That's risky... I think 'Elias N' has the updated answer that should work if you can't edit the JSON on the server-side
  • koceeng
    koceeng over 7 years
    did you change the JSON first? if not then you will get that error
  • koceeng
    koceeng over 7 years
    stackoverflow.com/users/6709464/elias-n answer was good, but for me, i think it take too much line of code. I prefer simple way more
  • user3478224
    user3478224 over 7 years
    Thank you so much @EliasN your answer works perfect!