解析JSON数组而无需包装类

时间:2018-12-11 19:57:07

标签: java json parsing arraylist wrapper

我正在尝试使用Gson将JSON数组解析为Java ArrayList。

{
  "fathers": [
    {
      "name": "Donald",
      "age": 47,
      "children": [
        {
          "name": "Johnny",
          "age": 6
        },
        {
          "name": "Donna",
          "age": 15
        },
        {
          "name": "Alan",
          "age": 21
        }
      ]
    },
    {
      "name": "George",
      "age": 35,
      "children": [
        {
          "name": "Cynthia",
          "age": 10
        },
        {
          "name": "Stacey",
          "age": 5
        },
        {
          "name": "Dewey",
          "age": 2
        }
      ]
    }
  ]
}

我正在尝试将“父亲”数组解析为ArrayList ...但是,由于父亲数组是由JSON对象包装的,因此我无法直接执行此操作。通常,我会这样做:

Type fathersListType = new TypeToken<ArrayList<Father>>(){}.getType();
fathersArrayList = gson.fromJson(fathersJson, fathersListType);

但是,由于父亲数组是由对象包装的,因此会出现此错误:

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

有没有一种方法可以解析所述数组,而不必声明包含“父”数组的包装器类?就像忽略包装对象或从中提取JSON数组一样。

2 个答案:

答案 0 :(得分:0)

类似的事情应该起作用:

String data = "{...}"; // Your JSON
JsonArray array = new JsonParser().parse(data).getAsJsonObject().get("fathers").getAsJsonArray();
List<Father> fathers = Arrays.asList(new Gson().fromJson(array, Father[].class));

Arrays.asList来自https://commons.apache.org/

答案 1 :(得分:0)

您可以将根对象解析为Map

Type rootType = new TypeToken<Map<String, List<Person>>>(){}.getType();
Map<String, List<Person>> root = gson.fromJson(fathersJson, rootType);
List<Person> fathersList = root.get("fathers");