1

We have the following json string:

jsonUserDataRecs=[{"G_ID1":1,"G_ID2":2,"G_ID3":3,"NAME":"g1"},{"G_ID1":4,"G_ID2":5,"G_ID3":5,"NAME":"g2"}]

Would like to convert it into the following data type:

ArrayList<USER_DATA_REC> userDataRecs;

We tried the following, but did not get any results:

userDataRecs = gson.fromJson(jsonUserDataRecs, new TypeToken<ArrayList<USER_DATA_REC>>() {}.getType());

When we run : userDataRecs.get(0).getNAME(), we did not get any results.

Any help will be greatly appreciated.

Thank you.

misman
  • 1,347
  • 3
  • 21
  • 39
Cemil Tatoglu
  • 65
  • 1
  • 10
  • Possible duplicate of [Google Gson - deserialize list object? (generic type)](http://stackoverflow.com/questions/5554217/google-gson-deserialize-listclass-object-generic-type) – Lyubomyr Shaydariv Apr 11 '17 at 11:58
  • what error do you get? And please share your USER_DATA_REC class – misman Apr 11 '17 at 11:59

1 Answers1

2

First make a POJO class:

public class UserDataRecord {
    public int G_ID1;
    public int G_ID2;
    public int G_ID3;
    public String NAME;
    public String getNAME() {
        return NAME;
    }
}

Next use gson to deserialize your json string like so:

UserDataRecord[] userDataRecords = gson.fromJson(jsonUserDataRecs, UserDataRecord[].class);

Now you have an array of the deserialized user data records. You can manually convert this to a list if you need to, or just iterate it using a normal for loop.

nbokmans
  • 5,492
  • 4
  • 35
  • 59