Parsing json error: java.lang.IllegalStateException: Not a JSON Object:

I am trying to parse a large json file which contains a bunch of cities (the following is the first two cities in the file):

  [
  {
    "id": 707860,
    "name": "Hurzuf",
    "country": "UA",
    "coord": {
      "lon": 34.283333,
      "lat": 44.549999
    }
  },
  {
    "id": 519188,
    "name": "Novinki",
    "country": "RU",
    "coord": {
      "lon": 37.666668,
      "lat": 55.683334
    }
  } ]

I want to get the IDs of cities whose “name” value matches a String:

    JsonParser parser = new JsonParser();

    JsonElement jsontree = parser.parse(new FileReader("C:/Users/kevin/Eclipse-workspace-new/kevinzhou_CSCI201_assignment3/WebContent/city.list.json"));
    JsonElement je = jsontree.getAsJsonObject();
    JsonArray ja = je.getAsJsonArray();
    for (Object o : ja)
    {
        JsonObject city = (JsonObject) o;
        if(cityName == city.get("name").getAsString())
        {
            System.out.println(city.get("id").getAsString());
        }
    }

However, I am getting the following error : java.lang.IllegalStateException: Not a JSON Object: and then it spits out the entire file after the colon.

Answer

change to

// JsonElement je = jsontree.getAsJsonObject();
JsonArray ja = jsontree.getAsJsonArray();

as it contains an Array at the top level

Leave a Reply

Your email address will not be published. Required fields are marked *