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?
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
Thx per un commento. Se questo programma funziona, cercherò presto GSON di prendere la mia decisione! – Jibi