How to parse JSONArray in Java with Json.simple?

I am trying to read a JSON file as follows:

{ "presentationName" : "Here some text", "presentationAutor" : "Here some text", "presentationSlides" : [ { "title" : "Here some text.", "paragraphs" : [ { "value" : "Here some text." }, { "value" : "Here some text." } ] }, { "title" : "Here some text.", "paragraphs" : [ { "value" : "Here some text.", "image" : "Here some text." }, { "value" : "Here some text." }, { "value" : "Here some text." } ] } ] } 

For school workouts, I decided to try using JSON.simple (from GoogleCode), but I'm open to other JSON libraries. I heard about Jackson and Gson: are they better than JSON.simple?

Here is my current Java code:

  Object obj = parser.parse(new FileReader( "file.json" )); JSONObject jsonObject = (JSONObject) obj; // First I take the global data String name = (String) jsonObject.get("presentationName"); String autor = (String) jsonObject.get("presentationAutor"); System.out.println("Name: "+name); System.out.println("Autor: "+autor); // Now we try to take the data from "presentationSlides" array JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides"); Iterator i = slideContent.iterator(); while (i.hasNext()) { System.out.println(i.next()); // Here I try to take the title element from my slide but it doesn't work! String title = (String) jsonObject.get("title"); System.out.println(title); } 

I check many examples (some of Stack!), But I never found a solution to my problem.

Maybe we can not do this with JSON.simple? What do you recommend?

+8
java json arrays
source share
2 answers

You never assign a new jsonObject value, so inside the loop it still refers to the complete data object. I think you need something like:

 JSONObject slide = i.next(); String title = (String)slide.get("title"); 
+11
source share

It works! thanks Russell. I will finish my exercise and try GSON to see the difference.

New code here:

  JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides"); Iterator i = slideContent.iterator(); while (i.hasNext()) { JSONObject slide = (JSONObject) i.next(); String title = (String)slide.get("title"); System.out.println(title); } 
+12
source share

All Articles