Android - Gson fromJson返回null

时间:2015-11-02 09:14:27

标签: android json gson

我有JSON模型架构(来自wikia api):

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

这是下载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"
    }
  }
}

这是我的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;
        }
    }
}

当我正在运行时:

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

测试对象内的HubInfo为null。我究竟做错了什么? 我正在使用Volley下载JSON。

1 个答案:

答案 0 :(得分:1)

正如您在JSON中看到的,实际上它不是列表,而是字典。因此,GSON无法真正将其映射到列表而不会丢失信息。

如果您将hubInfo对象的类型更改为此类型:

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

并且还要更改构造函数,它应该正常工作。

然后你可以通过以下方式获得一个值:

hubInfo.get("84");