user4596341
user4596341

Reputation:

Error on reading json file using JSON Simple Library

I am trying to read the following JSON file in java.

Here is my JSON File

 {
      "names": [
        {
          "no": 1,
          "name": "John"
        },
        {
          "no": 2,
          "name": "Paul"
        }
        ],
      "new_names": [
        {
          "no": 11,
          "name": "John"
        },
        {
          "no": 12,
          "name": "Paul"
        }
        ]
     }

Java Code:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;


public class ReadFile {


    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        JSONParser parser = new JSONParser();

        try {

            Object obj = parser.parse(new FileReader(
                    "D://data.json"));

            JSONObject jsonObject = (JSONObject) obj;


            JSONArray nameList = (JSONArray) jsonObject.get("names");


            System.out.println("\nnames:");
            Iterator<String> iterator = nameList.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I want to print names array, but I am getting following error:

java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String at ReadFile.main(ReadFile.java:34)

Upvotes: 0

Views: 184

Answers (3)

Saritha G
Saritha G

Reputation: 2608

Iteratoring from JsonObject..

So you should change below:

 Iterator<String> iterator = nameList.iterator();

to following:

 Iterator<JSONObject> iterator = nameList.iterator();

And iterate it using for loop, Iterator won't work for JSONArray.

Upvotes: 1

Trev Davies
Trev Davies

Reputation: 391

It is this line that is causing the problem:

Iterator<String> iterator = nameList.iterator();

Try using the following instead:

arrLength = nameList.Length()
for (int i = 0; i < arrLength; ++i) {
    JSONObject jsonObj = nameList.getJSONObject(i);
    System.out.println(jsonObj)
}

Upvotes: 0

Pragnani
Pragnani

Reputation: 20155

Your JSonArray nameList has has JSONObjects inside, not the strings,

You should do replace your String with JSONObject as mentioned in Exception trace

 Iterator<JSONObject > iterator = nameList.iterator();
            while (iterator.hasNext()) {
                 JSONObject jsonObjct= iterator.next()
                System.out.println(jsonObjct.getInt("no"));
                System.out.println(jsonObjct.getString("name"));
            }

Upvotes: 3

Related Questions