0

I am pulling a JSON string from a web service, that is styled in the version below. The JSON strings fields for the id's displayed would be arbitrary depending on what was sent in the get. I have followed some examples with gson where they talk about taking the json and running it into an object to handle the arbitrary field values. How to decode JSON with unknown field using Gson? and Dealing with randomly generated and inconsistent JSON field/key names using GSON

My question is, what do I do with the object once I create it to pull out specific fields. I had a custom class to pull the values from the inside of the object (id, name, profile) etc, but I'm lost in how I would be able to reference the two, or how I would extract the information from the object into an arraylist or something of the sort.

{
   "415943": {
      "id": 415943,
      "name": "Zoro Roronoa",
      "profileIconId": 580,
      "revisionDate": 1390848107000,
      "summonerLevel": 30
   },
   "19758386": {
      "id": 19758386,
      "name": "Zoro",
      "profileIconId": 535,
      "revisionDate": 1390855130000,
      "summonerLevel": 30
   }
}

Main.java

Gson gson = new Gson();
Object o = gson.fromJson(jsonStatsString, Object.class);
Community
  • 1
  • 1
Razgriz231
  • 105
  • 2
  • 10

1 Answers1

0

You can use your custom object that contains the mapped fields in the JSON, and have them converted to a List for you:

List<MyObject> items =
                gson.fromJson(json, new TypeToken<List<MyObject>>() { }.getType());
brwngrldev
  • 3,664
  • 3
  • 24
  • 45
  • I keep getting the error `"Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2"` – Razgriz231 Jan 29 '14 at 20:19
  • that's because it looks like the JSON is not an array, but rather an object that contains several objects. I would just take the string returned and replace the outer {} with [], so that it's an array. Then it should work. – brwngrldev Jan 29 '14 at 20:35
  • I didn't end up using the list object, but the `TypeToken` part of your answer is what I was looking for. – Razgriz231 Jan 30 '14 at 15:42