如何使用gson从嵌套的JSON文件创建Java对象?

时间:2015-08-30 10:28:14

标签: java android json parsing gson

我正在尝试使用gson来帮助我从JSON创建Java对象。一些示例将非常有用。

编辑1: 示例JSON:

{
  "version": "1.2.1",
  "updatedate": "16/08/2015",
  "comment": "Sample JSON.",
  "categories": [
    {
      "name": "Service",
      "id": 13,
      "taxesIDs": [],
      "taxTypeID": 3
    }
  ],
  "countries": [
    {
      "name": "Canada",
      "id": 4
    }
  ],
  "states": [
    {
      "name": "Yukon",
      "id": 151,
      "country": "Canada",
      "price": [
        {
          "name": "Sales",
          "id": 1,
          "taxes": [
            {
              "name": "General",
              "id": 1,
              "percent": 0
            },
            {
              "name": "Electronics",
              "id": 19,
              "percent": 5
            }
          ]
        },
        {
          "name": "Income",
          "id": 2,
          "taxes": [
            {},
            {}
          ]
        },
        {
          "name": "Service",
          "id": 3,
          "taxes": [
            {},
            {}
          ]
        }
      ]
    }
  ]
}

我想解析具有相同层次结构的上述JSON和Create Java Classes。 感谢。

2 个答案:

答案 0 :(得分:3)

使用this链接从json创建Java pojo类。

比使用这样的类,

YourObject obj = gson.fromJson(yourjsonstring, YourObject.class);

有关详情,请点击this链接。

答案 1 :(得分:1)

我们只需要以与JSON相同的方式构建Java类。特别是在我的情况下:

Class Source {
String version, comment, updatedate;
Category[] categories;
Country[] countries;
State[] states;
}

Class Category {
String name;
...
}

同样适用于州,价格,税收等级。

数据结构准备就绪后,可以使用@serhatSS提到的GSON。

String jsonString = new String(data);    // You have data in response
Gson gson = new Gson();
Source source = gson.fromJson(jsonString, Source.class);

现在,Source类将拥有其成员中的所有数据,并且可以通过以下方式访问:

Source.countries  // of type Country
Source.comment    // String

谢谢!

相关问题