How parsing JSONArray in Java with Json.simple?

匿名 (未验证) 提交于 2019-12-03 02:17:01

问题:

I try to read a JSON file like this:

{   "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."     }     ]   }   ] } 

It's for a school exercice, I choose to try to use JSON.simple (from GoogleCode) but I am open to another JSON libraries. I heard about Jackson and Gson: they are better than JSON.simple?

Here 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 a lot of example (some in Stack!) but I never found the solution of my problem.

Maybe we can't do that with JSON.simple? What do you recommend?

回答1:

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

JSONObject slide = i.next(); String title = (String)slide.get("title"); 


回答2:

It's working! Thx Russell. I will finish my exercice 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);         } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!