Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to parse a JSON to Gson Tree Model in Java?
Sometimes, we may need to parse a JSON into a Gson tree model in Java. For example, we may need to parse a JSON string into a tree model when we want to manipulate the JSON data in a more easy way.
The getAsJsonObject() Method
The Gson library is used to parse a JSON String into a Tree Model. We will be using the JsonParser to parse the JSON string into a Tree Model of type JsonElement.
We will be using the getAsJsonObject() method of JsonElement for getting the element as JsonObject, and the other is getAsJsonArray(), which is a method of JsonElement that can be used to get the element as JsonArray.
In this article, we will learn how to parse a JSON to a Gson tree model in Java. But before that, add the Gson library to the project. If you are using Maven, add below to your pom.xml file:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency>
If you do not use Maven, you can download the jar file from here.
Steps to Parse a JSON to a Gson Tree Model
The following are the steps to parse a JSON to a Gson tree model in Java:
- Import the Gson library as above.
- Create a JSON string.
- Use the JsonParser class to read the JSON string and turn it into a JsonElement.
- Convert the JsonElement into a JsonObject using the getAsJsonObject() method.
- Use the getAsJsonArray() method to turn the JsonElement into a JsonArray.
- Finally, display the JsonObject and JsonArray to see the results.
Example
Following is the code to parse a JSON to a Gson tree model in Java:
import com.google.gson.*;
public class ParseJsonToGsonTreeModelExample {
public static void main(String[] args) {
// JSON string to be parsed
String jsonString = "{"name":"Ansh","age":23,"skills":["Java","Python"]}";
// Create a JsonParser object
JsonParser jsonParser = new JsonParser();
// Parse the JSON string to a JsonElement
JsonElement jsonElement = jsonParser.parse(jsonString);
// Get the element as a JsonObject
JsonObject jsonObject = jsonElement.getAsJsonObject();
// Get the element as a JsonArray
JsonArray jsonArray = jsonObject.getAsJsonArray("skills");
// Print the JsonObject and JsonArray
System.out.println("JsonObject: " + jsonObject);
System.out.println("JsonArray: " + jsonArray);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Output
The output of the above code will be:
JsonObject: {"name":"Ansh","age":23,"skills":["Java","Python"]}
JsonArray: ["Java","Python"]