Tree Model prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes. It is a flexible approach and is analogous to DOM parser for XML.
Create Tree from JSON
JsonParser provides a pointer to the root node of the tree after reading the JSON. Root Node can be used to traverse the complete tree. Consider the following code snippet to get the root node of a provided JSON String.
//Create an JsonParser instance JsonParser parser = new JsonParser(); String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}"; //create tree from JSON JsonElement rootNode = parser.parse(jsonString);
Traversing Tree Model
Get each node using relative path to the root node while traversing the tree and process the data. The following code snippet shows how you can traverse a tree.
JsonObject details = rootNode.getAsJsonObject(); JsonElement nameNode = details.get("name"); System.out.println("Name: " +nameNode.getAsString()); JsonElement ageNode = details.get("age"); System.out.println("Age: " + ageNode.getAsInt());
Example
Create a Java class file named GsonTester in C:\>GSON_WORKSPACE.
File − GsonTester.java
import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class GsonTester { public static void main(String args[]) { String jsonString = "{\"name\":\"Mahesh Kumar\", \"age\":21,\"verified\":false,\"marks\": [100,90,85]}"; JsonParser parser = new JsonParser(); JsonElement rootNode = parser.parse(jsonString); if (rootNode.isJsonObject()) { JsonObject details = rootNode.getAsJsonObject(); JsonElement nameNode = details.get("name"); System.out.println("Name: " +nameNode.getAsString()); JsonElement ageNode = details.get("age"); System.out.println("Age: " + ageNode.getAsInt()); JsonElement verifiedNode = details.get("verified"); System.out.println("Verified: " + (verifiedNode.getAsBoolean() ? "Yes":"No")); JsonArray marks = details.getAsJsonArray("marks"); for (int i = 0; i < marks.size(); i++) { JsonPrimitive value = marks.get(i).getAsJsonPrimitive(); System.out.print(value.getAsInt() + " "); } } } }
Verify the result
Compile the classes using javac compiler as follows −
C:\GSON_WORKSPACE>javac GsonTester.java
Now run the GsonTester to see the result −
C:\GSON_WORKSPACE>java GsonTester
Verify the output.
Name: Mahesh Kumar Age: 21 Verified: No 100 90 85
No comments:
Post a Comment