I want to parse this JSON file in JAVA using GSON :
{
"descriptor" : {
"app1" : {
"name" : "mehdi",
"age" : 21,
"messages": ["msg 1","msg 2","msg 3"]
},
"app2" : {
"name" : "mkyong",
"age" : 29,
"messages": ["msg 11","msg 22","msg 33"]
},
"app3" : {
"name" : "amine",
"age" : 23,
"messages": ["msg 111","msg 222","msg 333"]
}
}
}
but I don't know how to acceed to the root element which is : descriptor, after that the app3 element and finally the name element.
I followed this tutorial http://www.mkyong.com/java/gson-streaming-to-read-and-write-json/, but it doesn't show the case of having a root and childs elements.
One thing that to be remembered while solving such problems is that in JSON file, a {
indicates a JSONObject
and a [
indicates JSONArray
. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.
The Gson JsonReader documentation explains how to handle parsing of JsonObjects
and JsonArrays
:
- Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
- Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().
I'm using gson 2.2.3
public class Main {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
JsonReader jsonReader = new JsonReader(new FileReader("jsonFile.json"));
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
if (name.equals("descriptor")) {
readApp(jsonReader);
}
}
jsonReader.endObject();
jsonReader.close();
}
public static void readApp(JsonReader jsonReader) throws IOException{
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String name = jsonReader.nextName();
System.out.println(name);
if (name.contains("app")){
jsonReader.beginObject();
while (jsonReader.hasNext()) {
String n = jsonReader.nextName();
if (n.equals("name")){
System.out.println(jsonReader.nextString());
}
if (n.equals("age")){
System.out.println(jsonReader.nextInt());
}
if (n.equals("messages")){
jsonReader.beginArray();
while (jsonReader.hasNext()) {
System.out.println(jsonReader.nextString());
}
jsonReader.endArray();
}
}
jsonReader.endObject();
}
}
jsonReader.endObject();
}
}
Source: Stackoverflow.com