0
# JSON Tree Model
1
2
Gson provides a tree-based API for building and manipulating JSON structures programmatically. This is useful when you need to modify JSON before serialization or after deserialization.
3
4
## JsonElement Hierarchy
5
6
```java { .api }
7
public abstract class JsonElement {
8
public abstract JsonElement deepCopy();
9
10
// Type checking methods
11
public boolean isJsonArray();
12
public boolean isJsonObject();
13
public boolean isJsonPrimitive();
14
public boolean isJsonNull();
15
16
// Conversion methods
17
public JsonObject getAsJsonObject();
18
public JsonArray getAsJsonArray();
19
public JsonPrimitive getAsJsonPrimitive();
20
public JsonNull getAsJsonNull();
21
22
// Primitive value extraction
23
public boolean getAsBoolean();
24
public Number getAsNumber();
25
public String getAsString();
26
public double getAsDouble();
27
public float getAsFloat();
28
public long getAsLong();
29
public int getAsInt();
30
public byte getAsByte();
31
public char getAsCharacter();
32
}
33
```
34
35
## JsonObject
36
37
Represents JSON objects with key-value pairs.
38
39
```java { .api }
40
public final class JsonObject extends JsonElement {
41
public JsonObject();
42
public JsonObject deepCopy();
43
44
// Adding elements
45
public void add(String property, JsonElement value);
46
public void addProperty(String property, String value);
47
public void addProperty(String property, Number value);
48
public void addProperty(String property, Boolean value);
49
public void addProperty(String property, Character value);
50
51
// Accessing elements
52
public JsonElement get(String memberName);
53
public JsonPrimitive getAsJsonPrimitive(String memberName);
54
public JsonArray getAsJsonArray(String memberName);
55
public JsonObject getAsJsonObject(String memberName);
56
57
// Management
58
public JsonElement remove(String property);
59
public boolean has(String memberName);
60
public Set<Map.Entry<String, JsonElement>> entrySet();
61
public Set<String> keySet();
62
public int size();
63
public boolean isEmpty();
64
}
65
```
66
67
**Usage:**
68
```java
69
// Create JSON object programmatically
70
JsonObject person = new JsonObject();
71
person.addProperty("name", "Alice");
72
person.addProperty("age", 30);
73
person.addProperty("active", true);
74
75
// Convert to string
76
Gson gson = new Gson();
77
String json = gson.toJson(person);
78
// Result: {"name":"Alice","age":30,"active":true}
79
80
// Access properties
81
String name = person.get("name").getAsString();
82
int age = person.get("age").getAsInt();
83
boolean active = person.get("active").getAsBoolean();
84
85
// Check if property exists
86
if (person.has("email")) {
87
String email = person.get("email").getAsString();
88
}
89
```
90
91
## JsonArray
92
93
Represents JSON arrays.
94
95
```java { .api }
96
public final class JsonArray extends JsonElement {
97
public JsonArray();
98
public JsonArray(int capacity);
99
public JsonArray deepCopy();
100
101
// Adding elements
102
public void add(JsonElement element);
103
public void add(Boolean bool);
104
public void add(Character character);
105
public void add(Number number);
106
public void add(String string);
107
108
// Accessing elements
109
public JsonElement get(int index);
110
111
// Management
112
public JsonElement remove(int index);
113
public boolean remove(JsonElement element);
114
public boolean contains(JsonElement element);
115
public int size();
116
public boolean isEmpty();
117
118
// Iteration
119
public Iterator<JsonElement> iterator();
120
}
121
```
122
123
**Usage:**
124
```java
125
// Create JSON array
126
JsonArray numbers = new JsonArray();
127
numbers.add(1);
128
numbers.add(2);
129
numbers.add(3);
130
131
// Convert to string
132
String json = gson.toJson(numbers);
133
// Result: [1,2,3]
134
135
// Access elements
136
for (int i = 0; i < numbers.size(); i++) {
137
int value = numbers.get(i).getAsInt();
138
System.out.println(value);
139
}
140
141
// Using iterator
142
for (JsonElement element : numbers) {
143
int value = element.getAsInt();
144
System.out.println(value);
145
}
146
```
147
148
## JsonPrimitive
149
150
Represents JSON primitive values (strings, numbers, booleans).
151
152
```java { .api }
153
public final class JsonPrimitive extends JsonElement {
154
public JsonPrimitive(Boolean bool);
155
public JsonPrimitive(Number number);
156
public JsonPrimitive(String string);
157
public JsonPrimitive(Character c);
158
public JsonPrimitive deepCopy();
159
160
public boolean isBoolean();
161
public boolean isNumber();
162
public boolean isString();
163
}
164
```
165
166
**Usage:**
167
```java
168
JsonPrimitive stringValue = new JsonPrimitive("Hello");
169
JsonPrimitive numberValue = new JsonPrimitive(42);
170
JsonPrimitive boolValue = new JsonPrimitive(true);
171
172
// Check types
173
if (stringValue.isString()) {
174
String str = stringValue.getAsString();
175
}
176
177
if (numberValue.isNumber()) {
178
int num = numberValue.getAsInt();
179
double dbl = numberValue.getAsDouble();
180
}
181
```
182
183
## JsonNull
184
185
Represents JSON null values.
186
187
```java { .api }
188
public final class JsonNull extends JsonElement {
189
public static final JsonNull INSTANCE;
190
public JsonNull deepCopy();
191
}
192
```
193
194
**Usage:**
195
```java
196
JsonObject obj = new JsonObject();
197
obj.add("nullValue", JsonNull.INSTANCE);
198
```
199
200
## Tree Conversion
201
202
Convert between objects and JSON trees:
203
204
```java { .api }
205
// Object to tree
206
public JsonElement toJsonTree(Object src);
207
public JsonElement toJsonTree(Object src, Type typeOfSrc);
208
209
// Tree to object
210
public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException;
211
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException;
212
public <T> T fromJson(JsonElement json, TypeToken<T> typeOfT) throws JsonSyntaxException;
213
```
214
215
**Usage:**
216
```java
217
// Object to tree
218
Person person = new Person("Bob", 25);
219
JsonElement tree = gson.toJsonTree(person);
220
221
// Modify the tree
222
JsonObject obj = tree.getAsJsonObject();
223
obj.addProperty("email", "bob@example.com");
224
225
// Tree back to object
226
Person modifiedPerson = gson.fromJson(obj, Person.class);
227
228
// Tree to JSON string
229
String json = gson.toJson(tree);
230
```
231
232
## JsonParser
233
234
Utility for parsing JSON strings into JsonElement trees.
235
236
```java { .api }
237
public final class JsonParser {
238
public static JsonElement parseString(String json) throws JsonSyntaxException;
239
public static JsonElement parseReader(Reader reader) throws JsonIOException, JsonSyntaxException;
240
public static JsonElement parseReader(JsonReader reader) throws JsonIOException, JsonSyntaxException;
241
}
242
```
243
244
**Usage:**
245
```java
246
String json = "{\"name\":\"Alice\",\"age\":30}";
247
JsonElement element = JsonParser.parseString(json);
248
249
if (element.isJsonObject()) {
250
JsonObject obj = element.getAsJsonObject();
251
String name = obj.get("name").getAsString();
252
}
253
```
254
255
## JsonStreamParser
256
257
Streaming parser for processing multiple JSON values from a single reader.
258
259
```java { .api }
260
public final class JsonStreamParser implements Iterator<JsonElement> {
261
public JsonStreamParser(Reader reader);
262
public JsonStreamParser(String json);
263
264
public boolean hasNext();
265
public JsonElement next() throws JsonParseException;
266
}
267
```
268
269
**Usage:**
270
```java
271
String multipleJson = "{\"name\":\"Alice\"} {\"name\":\"Bob\"} [1,2,3]";
272
JsonStreamParser parser = new JsonStreamParser(multipleJson);
273
274
while (parser.hasNext()) {
275
JsonElement element = parser.next();
276
System.out.println(element);
277
}
278
```
279
280
## Complex Tree Manipulation
281
282
**Building nested structures:**
283
```java
284
JsonObject address = new JsonObject();
285
address.addProperty("street", "123 Main St");
286
address.addProperty("city", "Springfield");
287
288
JsonObject person = new JsonObject();
289
person.addProperty("name", "John");
290
person.add("address", address);
291
292
JsonArray hobbies = new JsonArray();
293
hobbies.add("reading");
294
hobbies.add("swimming");
295
person.add("hobbies", hobbies);
296
```
297
298
**Traversing complex structures:**
299
```java
300
JsonObject root = JsonParser.parseString(complexJson).getAsJsonObject();
301
302
for (Map.Entry<String, JsonElement> entry : root.entrySet()) {
303
String key = entry.getKey();
304
JsonElement value = entry.getValue();
305
306
if (value.isJsonObject()) {
307
JsonObject nested = value.getAsJsonObject();
308
// Process nested object
309
} else if (value.isJsonArray()) {
310
JsonArray array = value.getAsJsonArray();
311
for (JsonElement item : array) {
312
// Process array item
313
}
314
}
315
}
316
```