What is the role of the JsonObject class in GSON?
A) To represent a JSON object in a tree structure
B) To serialize Java objects to JSON
C) To handle HTTP requests
D) To manage database connections
Answer:
A) To represent a JSON object in a tree structure
Explanation:
The JsonObject
class in GSON is used to represent a JSON object in a tree structure. It allows you to create and manipulate JSON objects programmatically by adding properties, retrieving values, and navigating the JSON structure.
For example:
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "John");
jsonObject.addProperty("age", 30);
String jsonString = jsonObject.toString();
In this example, a JsonObject
is created with two properties: “name” and “age”. The JSON object is then converted to a JSON string using the toString()
method.