Alex Ruiz
Alex Ruiz

Reputation: 19

How to read a JSON file in Java? with the JSON.simple library

I have the following JSON text. How can I read it?

{"animal": { "type": "Panther", "name": "Sylvester", "age": 12 }}

I've tried to do this but it doesn't work.

It throws this Exception

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

FAILURE: Build failed with an exception.

What went wrong:

Execution failed for task ':Json_to_XML.main()'. Process 'command 'C:/Program Files/Java/jdk1.8.0_181/bin/java.exe'' finished with non-zero exit value 1

public static void main(String[] args)
        {

            //JSON parser object to parse read file
            JSONParser jsonParser = new JSONParser();
            try {
                String ruta ="C:\\Users\\Usuari\\Desktop\\documento.json";
                Object obj = jsonParser.parse (new FileReader (ruta));

                JSONObject jsonObject  = (JSONObject) obj;

                String tipo = (String) jsonObject.get("type");
                System.out.println(tipo);

                String nombre = (String) jsonObject.get("name");
                System.out.println(nombre);

                Long edad = (Long) jsonObject.get("age");
                System.out.println(edad);

                JSONArray leng= (JSONArray) jsonObject.get("animal");
                Iterator iterator =leng.iterator();
                while (iterator.hasNext()) {
                    System.out.println(iterator.next());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

Upvotes: 1

Views: 138

Answers (1)

Piotr Niewinski
Piotr Niewinski

Reputation: 1347

You have two possible way of solving your issue:

You can convert object in .json into array, you will need to change this:

{"animal": { "type": "Panther", "name": "Sylvester", "age": 12 }}

To that:

{"animal": [{"type": "Panther", "name": "Sylvester", "age": 12 }]}

Unless you want to keep json intact, then consider the following change from:

JSONArray leng= (JSONArray) jsonObject.get("animal");
Iterator iterator =leng.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}

To:

JSONObject leng= (JSONObject) jsonObject.get("animal");
System.out.println(leng.get("name") + " - " + leng.get("type"));

Upvotes: 1

Related Questions