迭代 JsonObject 属性
我想用 Gson 遍历大包装 JsonObject
.我的最终目标是在内部 "unterfeld"
对象中获取所有现有三位数 code
整数的 ArrayList
,但这不会有问题一旦我可以遍历外部对象的属性.
I would like to iterate through the big wrapping JsonObject
with Gson. My final aim is to get an ArrayList
of all existing three digit code
integers in the inner "unterfeld"
objects, but that will be no problem once I can iterate through the outer object's properties.
{
"something1": {
"bezeichnung": "something1",
"unterfeld": [
{
"bezeichnung": "bla1",
"unterregionen": [
],
"code": 111
},
{
"bezeichnung": "bla2",
"unterregionen": [
],
"code": 222
}
],
"code": 3
},
"something2": {
"bezeichnung": "something2",
"unterfeld": [
{
"bezeichnung": "bla3",
"unterregionen": [
],
"code": 333
}
],
"code": 6
},
"something3": {
"bezeichnung": "something3",
"unterfeld": [
{
"bezeichnung": "bla4",
"unterregionen": [
],
"code": 444
},
{
"bezeichnung": "bla5",
"unterregionen": [
],
"code": 555
},
{
"bezeichnung": "bla6",
"unterregionen": [
],
"code": 666
}
],
"code": 9
}
}
有什么好办法吗?
推荐答案
你可以使用entrySet
迭代最外层 JsonObject
的成员.
JsonObject object;
ArrayList<Integer> codes = new ArrayList<Integer>();
for (Map.Entry<String,JsonElement> entry : object.entrySet()) {
JsonArray array = entry.getValue().getAsJsonObject().getAsJsonArray("unterfeld");
for (JsonElement codeHolder : array) {
codes.add(codeHolder.getAsJsonObject().getAsJsonPrimitive("code").getAsInt());
}
}
相关文章