2013-09-16 12 views
8

próbie odczytania pliku JSON tak:Jak parsować JSONArray w Javie z Json.simple?

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

To o sprawowaniu szkolnego, postanawiam spróbować użyć JSON.simple (od GoogleCode), ale jestem otwarty na kolejnych bibliotek JSON. Słyszałem o Jacksonie i Gsonie: są lepsze od JSON.simple?

Oto mój bieżący kod Java:

 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); 
     } 

sprawdzić wiele Przykład (niektóre w stos!), Ale nigdy nie znalazłem rozwiązania mojego problemu.

Może nie możemy tego zrobić z JSON.simple? Co polecasz?

+0

Jest czysto religijne argumentem dla mnie, ale wolę [Google GSON] (https://code.google.com/p/google-gson/) ponad inne parsery JSON. – david99world

+0

Thx za komentarz. Jeśli ten program działa, wkrótce spróbuję GSON, aby sam podjąć decyzję! – Jibi

Odpowiedz

11

Nigdy nie przypisz nowej wartości do jsonObject, więc wewnątrz pętli nadal odnosi się do pełnego obiektu danych. Myślę, że chcesz coś takiego:

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

Próbuję i wrócę wkrótce;) – Jibi

12

Działa! Thx Russell. Skończę ćwiczenie i spróbuję GSON, żeby zobaczyć różnicę.

Nowy kod tutaj:

 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); 
     }