user5305868
user5305868

Reputation:

JsonArray Nested Object -> Gson

I have this Json File:

{
  "code": "#0",
  "data": {
    "list": [
      "Chris",
      "Matt"
    ],
    "time": 1453318488122
  },
  "millis": "1453492643260"
}

In Java using Gson how do I access the "data" part, then "list" and turn it into an ArrayList? I have tried looking online and they are all showing things way too complicated for what I want, like serializing a class into Json. I don't want that.. How do I access "List" array inside of "data" object and put into an ArrayList?

Upvotes: 0

Views: 59

Answers (2)

Mateusz Herych
Mateusz Herych

Reputation: 1605

You can serialize/deserialize such JSON without any additional adapter classes if you define a class like this one.

class MyPojo {
  String code;
  long millis;
  Data data;

  static class Data {
    List<String> list;
    long time;
  }
}

(+ eventually @SerializedName annotations if your strategy requires them)

Upvotes: 0

NG.
NG.

Reputation: 22904

JsonObject fullObject = new JsonParser().parse(yourFileData).getAsJsonObject();
JsonObject data = fullObject.getAsJsonObject('data');
JsonArray dataList = data.getAsJsonArray('list');

From there you can use dataList and iterate the elements.

Upvotes: 1

Related Questions