I thought this would be simple but it keeps crashing with InvocationTargetException
at reader.hasNext()
.
File jsonInputFile = new File(root "/dicts/phrases.json");
JsonReader reader = new JsonReader(new FileReader(jsonInputFile));
while (reader.hasNext()) {
System.out.println(reader.nextName());
}
What exactly is wrong with this? The while loop just goes on forever despite the json file only have one line.
CodePudding user response:
Since it seems to be reading the JSON and it is encountering a BEGIN_TOKEN rather than JsonToken.NAME type
Could you try the below:
while (jsonReader.hasNext())
{
JsonToken nextToken = jsonReader.peek();
if (JsonToken.BEGIN_OBJECT.equals(nextToken)) {
jsonReader.beginObject();
} else if (JsonToken.NAME.equals(nextToken)) {
String name = jsonReader.nextName();
System.out.println("Token KEY >>>> " name);
} else if (JsonToken.STRING.equals(nextToken)) {
String value = jsonReader.nextString();
System.out.println("Token Value >>>> " value);
} else if (JsonToken.NUMBER.equals(nextToken)) {
long value = jsonReader.nextLong();
System.out.println("Token Value >>>> " value);
} else if (JsonToken.NULL.equals(nextToken)) {
jsonReader.nextNull();
System.out.println("Token Value >>>> null");
} else if (JsonToken.END_OBJECT.equals(nextToken)) {
jsonReader.endObject();
}
}