在没有包装器的情况下解析 JSON 数组 class
Parsing a JSON array WITHOUT a wrapper class
我正在尝试使用 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
}
]
}
]
}
我正在尝试将 "fathers" 数组解析为 ArrayList...但是,我不能直接这样做,因为 fathers 数组被 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 $
有没有一种方法可以解析所述数组,而不必声明包含 "fathers" 数组的包装器 class?比如忽略包装对象,或从中提取 JSON 数组。
像这样的东西应该可以工作:
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/
您可以将根对象解析为 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");
我正在尝试使用 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
}
]
}
]
}
我正在尝试将 "fathers" 数组解析为 ArrayList...但是,我不能直接这样做,因为 fathers 数组被 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 $
有没有一种方法可以解析所述数组,而不必声明包含 "fathers" 数组的包装器 class?比如忽略包装对象,或从中提取 JSON 数组。
像这样的东西应该可以工作:
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/
您可以将根对象解析为 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");