Marcin Bortel
Marcin Bortel

Reputation: 1259

Android - Gson fromJson returns null

i've got JSON model schema (this is from wikia api):

{
    "HubInfo": [
    {
      "id": "integer",
      "name": "string",
      "url": "string",
      "language": "string"
    }
    ]
}

This is result of download JSON:

{
  "list": {
    "84": {
      "id": 84,
      "name": "Music Hub",
      "url": "http://musichub.wikia.com/",
      "language": "en"
    },
    "646052": {
      "id": 646052,
      "name": "Books Hub",
      "url": "http://bookshub.wikia.com/",
      "language": "en"
    },
    "952281": {
      "id": 952281,
      "name": "Lifestyle Hub",
      "url": "http://lifestylehub.wikia.com/",
      "language": "en"
    },
    "952442": {
      "id": 952442,
      "name": "Movies Hub",
      "url": "http://movieshub.wikia.com/",
      "language": "en"
    },
    "952445": {
      "id": 952445,
      "name": "Comics Hub",
      "url": "http://comicshub.wikia.com/",
      "language": "en"
    },
    "955764": {
      "id": 955764,
      "name": "Games Hub ",
      "url": "http://gameshub.wikia.com/",
      "language": "en"
    },
    "957447": {
      "id": 957447,
      "name": "TV Hub ",
      "url": "http://tvhub.wikia.com/",
      "language": "en"
    },
    "1114909": {
      "id": 1114909,
      "name": "Huddler Hub",
      "url": "http://huddlerhub.wikia.com/",
      "language": "en"
    },
    "1162644": {
      "id": 1162644,
      "name": "Rupertproducttest Wikia",
      "url": "http://rupertproducttest.wikia.com/",
      "language": "en"
    }
  }
}

And this is my POJO:

public final class Test {
    public final HubInfo hubInfo[];

    public Test(HubInfo[] hubInfo){
        this.hubInfo = hubInfo;
    }

    public static final class HubInfo {
        public final String id;
        public final String name;
        public final String url;
        public final String language;

        public HubInfo(String id, String name, String url, String language){
            this.id = id;
            this.name = name;
            this.url = url;
            this.language = language;
        }
    }
}

When i'm running this:

Test test = gson.fromJson(json, Test.class);

HubInfo inside test object is null. What am i doing wrong? I'm using Volley to download JSON.

Upvotes: 1

Views: 275

Answers (1)

Daniel Zolnai
Daniel Zolnai

Reputation: 16910

As you can see in the JSON, practically it is not a list, but a dictionary. So GSON can't really map that to a list without losing information.

If you change the type of your hubInfo object to this type:

@SerializedName("list")
Map<String, HubInfo> hubInfo;

And also change the constructor, it should be working.

Then you can get a value by:

hubInfo.get("84");

Upvotes: 1

Related Questions