2013-09-16 10 views
8

provo a leggere un file JSON come questo:Come analizzare JSONArray in Java con 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." 
    } 
    ] 
    } 
    ] 
} 

E 'per un esercizio di scuola, ho scelto di provare ad usare JSON.simple (da GoogleCode) ma sono aperto ad un altro librerie JSON. Ho sentito parlare di Jackson e Gson: sono meglio di JSON.simple?

Ecco il mio codice Java corrente:

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

verifico un sacco di esempio (alcuni in Stack!), Ma non ho mai trovato la soluzione del mio problema.

Forse non possiamo farlo con JSON.simple? Che cosa mi consiglia?

+0

Questo è puramente un argomento religioso per me, ma io preferisco di gran lunga [Google GSON] (https://code.google.com/p/google-gson/) su altri parser JSON. – david99world

+0

Thx per un commento. Se questo programma funziona, cercherò presto GSON di prendere la mia decisione! – Jibi

risposta

11

Non si assegna mai un nuovo valore a jsonObject, quindi all'interno del loop si riferisce ancora all'oggetto dati completo. Penso che tu voglia qualcosa come:

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

Ci provo e torno presto;) – Jibi

12

Funziona! Thx Russell. Finirò il mio allenamento e cercherò GSON di vedere la differenza.

Nuovo codice qui:

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