提问人:elementmg 提问时间:9/30/2023 更新时间:9/30/2023 访问量:34
使用 Gson JsonReader 深入钻取 JSON 文件
Drilling deep into JSON file with Gson JsonReader
问:
我是第一次使用 JsonReader,我正在尝试获取数组中的值。基本上,我发现深入到JSON文件中,似乎有大量的重复和循环。肯定有更好的方法可以做到这一点吗?这看起来很可怕。有没有办法直接读取和访问(例如 DocumentList 数组)内容?我确信,当我看到下面的混乱时,我不知道自己在做什么。
有没有办法简单地遍历文档对象并获取所需的值,执行工作,它们移动到下一个文档对象?
streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8.toString());
jsonReader = new JsonReader(streamReader);
jsonReader.beginObject();
while (jsonReader.hasNext()) {
final String name = jsonReader.nextName();
if ("Level1".equals(name)) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
final String listName = jsonReader.nextName();
if ("DocumentList".equals(listName)) {
jsonReader.beginArray();
while (jsonReader.hasNext()) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
final String key = jsonReader.nextName();
if ("Documents".equals(key)) {
jsonReader.beginObject();
while (jsonReader.hasNext()) {
final String fieldKey = jsonReader.nextName();
if ("ID".equals(fieldKey)) {
report.id = jsonReader.nextString();
}
else if ("CName".equals(fieldKey)) {
report.CName = jsonReader.nextString();
}
else if ("Ext".equals(fieldKey)) {
report.Ext = jsonReader.nextString();
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
//DO work on report (contents of "Documents")
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
}
jsonReader.endArray();
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
}
else {
jsonReader.skipValue();
}
}
jsonReader.endObject();
这是我使用的示例 JSON 格式
{
"Level1": {
"DocumentList": [
{
"Documents": {
"ID": "123",
"CName": "name",
"SecurityStatus": "P",
"Ext": "abc",
"Prefix": "pre",
}
},
{
"Documents": {
"ID": "321",
"CName": "name2",
"SecurityStatus": "Q",
"Ext": "bca",
"Prefix": "post",
}
},
{
"Documents": {
"ID": "456",
"CName": "name3",
"SecurityStatus": "S",
"Ext": "def",
"Prefix": "dur",
}
},
]
}
}
答: 暂无答案
评论