简体   繁体   中英

Read a simple JSON file with GSON JsonReader

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.

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();
 
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM