1

I am trying to read the values from a JSON file to array for further processing. I am using JSON-Smart 1.2.0 library for the same. Due to some restrictions, I can not use the 2.0 version.

I am getting the following exception.

java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to net.minidev.json.JSONObject

I am even tried using JSONArray instead of JSONObject. What I am doing wrong over here? Is this correct way to read json content?

Below is the java code.

JSONObject json = (JSONObject) JSONValue.parseWithException(browsers);
JSONArray array = (JSONArray) json.get("friends");

for (int i = 0; i < array.size(); i++) {
    JSONObject cap = (JSONObject) array.get(i);
    String first = (String) cap.get("name");
    System.out.println(first);
}

Below is the json file content.

[
  {
    "friends": [
      {
        "id": 0,
        "name": "test1"
      },
      {
        "id": 1,
        "name": "test2"
      }
    ]
  }
]
Purus
  • 5,701
  • 9
  • 50
  • 89

1 Answers1

3

Your JSON contains an array which has one single object element so you should parse it like that:

JSONArray root = (JSONArray) JSONValue.parseWithException(json);
JSONObject rootObj = (JSONObject) root.get(0);
JSONArray array = (JSONArray) rootObj.get("friends");

for (int i = 0; i < array.size(); i++) {
    JSONObject cap = (JSONObject) array.get(i);
    String first = (String) cap.get("name");
    System.out.println(first);
}

If it can have more elements add a for loop instead of root.get(0).

cy3er
  • 1,699
  • 11
  • 14