Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (13.1k points)

Can anyone help me how I can able to read the JSON file using json simple library in Java? I was trying it with the below code, but it is throwing an error:

package javaapplication1;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

import java.util.Iterator;

import org.json.simple.JSONArray;

import org.json.simple.JSONObject;

import org.json.simple.parser.JSONParser;

import org.json.simple.parser.ParseException;

public class JavaApplication1 {

    public static void main(String[] args) {

        JSONParser parser = new JSONParser();

        try {     

            Object obj = parser.parse(new FileReader("c:\\file.json"));

            JSONObject jsonObject =  (JSONObject) obj;

            String name = (String) jsonObject.get("name");

            System.out.println(name);

            String city = (String) jsonObject.get("city");

            System.out.println(city);

            String job = (String) jsonObject.get("job");

            System.out.println(job);

            // loop array

            JSONArray cars = (JSONArray) jsonObject.get("cars");

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

            while (iterator.hasNext()) {

             System.out.println(iterator.next());

            }

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } catch (ParseException e) {

            e.printStackTrace();

        }

    }

}

The error:

Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject at javaapplication1.JavaApplication1.main(JavaApplication1.java:24)

Any help would be appreciated.

1 Answer

0 votes
by (26.7k points)

You can use the below code snippet which will help you achieve what you want:

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json"));

  for (Object o : a)

  {

    JSONObject person = (JSONObject) o;

    String name = (String) person.get("name");

    System.out.println(name);

    String city = (String) person.get("city");

    System.out.println(city);

    String job = (String) person.get("job");

    System.out.println(job);

    JSONArray cars = (JSONArray) person.get("cars");

    for (Object c : cars)

    {

      System.out.println(c+"");

    }

  }

I hope this will help.

Want to become a Java Expert? Join Java Certification now!!

Related questions

0 votes
1 answer
+10 votes
2 answers
asked May 30, 2019 in Java by tommas (1k points)
0 votes
1 answer
asked Nov 12, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 14, 2019 in Java by Anvi (10.2k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...