How do I parse a JSONArray in Java with Json.simple?

前端 未结 3 535
再見小時候
再見小時候 2020-12-30 04:35

I am trying to read a JSON file like this:

{
  \"presentationName\" : \"Here some text\",
  \"presentationAutor\" : \"Here some text\",
  \"presentationSlide         


        
相关标签:
3条回答
  • 2020-12-30 05:05

    For Gson you can paste your json file here : https://www.freecodeformat.com/json2pojo.php Create appropriate pojo classes and then use this code :

    Gson gson = new Gson();
    
        try (Reader reader = new FileReader("pathToYourFile.json")) {
    
            // Convert JSON File to Java Object
            Root root = gson.fromJson(reader, Root.class);
    
            // print staff you need
            System.out.println(root.getCommands().get(0).getName());
    
        } catch (IOException e) {
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-30 05:18

    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);
            }
    
    0 讨论(0)
  • 2020-12-30 05:22

    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");
    
    0 讨论(0)
提交回复
热议问题