1

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.

2
  • you are getting an array as an object Commented Mar 7, 2019 at 4:58
  • And which JSON parser would this be? Commented Mar 7, 2019 at 4:58

2 Answers 2

4

change to

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

as it contains an Array at the top level

Sign up to request clarification or add additional context in comments.

Comments

3

Try below given code to handle both condition

if (jsontree instanceof JsonObject) {
    JsonObject  jobject = new JsonObject(jsontree .getAsJsonObject());
 } else if (jsontree instanceof JsonArray) {
    JsonArray  jarray =  new JsonArray(jsontree .getAsJsonArray());
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.