I'm working with JsonReader for the first time and I'm trying to grab values within an array. Basically what I've found is to drill deep down into a JSON file it seems like there is a ton of repetition and loops. Surely there is a better way to do this? This looks plain awful. Is there a way to read and access (for example the DocumentList array) things directly? I'm convinced I don't know what I'm doing when I look at the mess below.
Is there a way to simply just loop through the documents objects and grab the required values, do work, them move to the next documents object?
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();
Here is the sample JSON format that im working with
{
"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",
}
},
]
}
}