0
# AST Serialization
1
2
JavaParser provides comprehensive serialization capabilities for converting AST nodes to and from JSON format. This enables storing, transmitting, and reconstructing Abstract Syntax Trees for various applications including code analysis, transformation tools, and persistent storage.
3
4
## Capabilities
5
6
### JSON Serialization
7
8
Convert AST nodes to JSON representation for storage or transmission.
9
10
```java { .api }
11
/**
12
* Serializer for converting AST nodes to JSON format
13
*/
14
public class JavaParserJsonSerializer {
15
16
/**
17
* Create serializer with default configuration
18
*/
19
public JavaParserJsonSerializer();
20
21
/**
22
* Serialize AST node to JSON string
23
* @param node AST node to serialize
24
* @return JSON string representation
25
*/
26
public String serialize(Node node);
27
28
/**
29
* Serialize AST node to JSON and write to output stream
30
* @param node AST node to serialize
31
* @param out Output stream to write JSON
32
* @throws IOException if writing fails
33
*/
34
public void serialize(Node node, OutputStream out) throws IOException;
35
36
/**
37
* Serialize AST node to JSON and write to writer
38
* @param node AST node to serialize
39
* @param writer Writer to output JSON
40
* @throws IOException if writing fails
41
*/
42
public void serialize(Node node, Writer writer) throws IOException;
43
}
44
```
45
46
**Usage Examples:**
47
48
```java
49
import com.github.javaparser.StaticJavaParser;
50
import com.github.javaparser.ast.CompilationUnit;
51
import com.github.javaparser.serialization.JavaParserJsonSerializer;
52
53
// Parse Java code
54
CompilationUnit cu = StaticJavaParser.parse("""
55
public class Example {
56
public void hello() {
57
System.out.println("Hello World");
58
}
59
}
60
""");
61
62
// Serialize to JSON
63
JavaParserJsonSerializer serializer = new JavaParserJsonSerializer();
64
String json = serializer.serialize(cu);
65
System.out.println(json);
66
67
// Serialize to file
68
try (FileOutputStream fos = new FileOutputStream("ast.json")) {
69
serializer.serialize(cu, fos);
70
}
71
```
72
73
### JSON Deserialization
74
75
Reconstruct AST nodes from JSON representation.
76
77
```java { .api }
78
/**
79
* Deserializer for converting JSON back to AST nodes
80
*/
81
public class JavaParserJsonDeserializer {
82
83
/**
84
* Create deserializer with default configuration
85
*/
86
public JavaParserJsonDeserializer();
87
88
/**
89
* Deserialize JSON string to AST node
90
* @param json JSON string to deserialize
91
* @return Reconstructed AST node
92
* @throws JsonProcessingException if JSON parsing fails
93
*/
94
public Node deserialize(String json) throws JsonProcessingException;
95
96
/**
97
* Deserialize JSON from input stream to AST node
98
* @param in Input stream containing JSON
99
* @return Reconstructed AST node
100
* @throws IOException if reading fails
101
* @throws JsonProcessingException if JSON parsing fails
102
*/
103
public Node deserialize(InputStream in) throws IOException, JsonProcessingException;
104
105
/**
106
* Deserialize JSON from reader to AST node
107
* @param reader Reader containing JSON
108
* @return Reconstructed AST node
109
* @throws IOException if reading fails
110
* @throws JsonProcessingException if JSON parsing fails
111
*/
112
public Node deserialize(Reader reader) throws IOException, JsonProcessingException;
113
114
/**
115
* Deserialize JSON to specific AST node type
116
* @param json JSON string to deserialize
117
* @param nodeType Expected AST node type
118
* @return Reconstructed AST node of specified type
119
* @throws JsonProcessingException if JSON parsing fails
120
* @throws ClassCastException if JSON doesn't represent expected type
121
*/
122
public <T extends Node> T deserialize(String json, Class<T> nodeType)
123
throws JsonProcessingException;
124
}
125
```
126
127
**Usage Examples:**
128
129
```java
130
import com.github.javaparser.serialization.JavaParserJsonDeserializer;
131
132
JavaParserJsonDeserializer deserializer = new JavaParserJsonDeserializer();
133
134
// Deserialize from JSON string
135
String json = "..."; // JSON representation of AST
136
Node reconstructedNode = deserializer.deserialize(json);
137
138
// Deserialize to specific type
139
CompilationUnit cu = deserializer.deserialize(json, CompilationUnit.class);
140
141
// Deserialize from file
142
try (FileInputStream fis = new FileInputStream("ast.json")) {
143
Node node = deserializer.deserialize(fis);
144
}
145
146
// Round-trip example: serialize and deserialize
147
CompilationUnit original = StaticJavaParser.parse("public class Test {}");
148
JavaParserJsonSerializer serializer = new JavaParserJsonSerializer();
149
String json = serializer.serialize(original);
150
151
CompilationUnit restored = deserializer.deserialize(json, CompilationUnit.class);
152
// restored is functionally equivalent to original
153
```
154
155
### Serialization Configuration
156
157
Control serialization behavior and format options.
158
159
```java { .api }
160
/**
161
* Configuration options for JSON serialization
162
*/
163
public class JsonSerializationConfiguration {
164
165
/**
166
* Create default configuration
167
*/
168
public JsonSerializationConfiguration();
169
170
/**
171
* Enable/disable pretty printing of JSON output
172
* @param prettyPrint true to format JSON with indentation
173
* @return This configuration for chaining
174
*/
175
public JsonSerializationConfiguration setPrettyPrint(boolean prettyPrint);
176
177
/**
178
* Include/exclude position information in serialized JSON
179
* @param includePositions true to include range/position data
180
* @return This configuration for chaining
181
*/
182
public JsonSerializationConfiguration setIncludePositions(boolean includePositions);
183
184
/**
185
* Include/exclude comments in serialized JSON
186
* @param includeComments true to include comment nodes
187
* @return This configuration for chaining
188
*/
189
public JsonSerializationConfiguration setIncludeComments(boolean includeComments);
190
}
191
```
192
193
### Use Cases
194
195
JSON serialization enables several important use cases:
196
197
**Persistent Storage:**
198
```java
199
// Store parsed AST for later processing
200
CompilationUnit cu = StaticJavaParser.parse(sourceFile);
201
String json = serializer.serialize(cu);
202
database.store(fileName, json);
203
204
// Later: retrieve and reconstruct AST
205
String storedJson = database.retrieve(fileName);
206
CompilationUnit restored = deserializer.deserialize(storedJson, CompilationUnit.class);
207
```
208
209
**Distributed Processing:**
210
```java
211
// Send AST over network for remote analysis
212
String json = serializer.serialize(compilationUnit);
213
httpClient.post("/analyze", json);
214
215
// Receive modified AST back
216
String modifiedJson = httpClient.receive();
217
CompilationUnit modified = deserializer.deserialize(modifiedJson, CompilationUnit.class);
218
```
219
220
**Code Analysis Pipelines:**
221
```java
222
// Serialize intermediate results in multi-stage analysis
223
CompilationUnit parsed = StaticJavaParser.parse(source);
224
String stage1 = serializer.serialize(parsed);
225
226
// Stage 2: symbol resolution (different process/machine)
227
CompilationUnit stage1AST = deserializer.deserialize(stage1, CompilationUnit.class);
228
// ... perform symbol resolution ...
229
String stage2 = serializer.serialize(stage1AST);
230
231
// Stage 3: code transformation
232
CompilationUnit stage2AST = deserializer.deserialize(stage2, CompilationUnit.class);
233
// ... perform transformations ...
234
```
235
236
## JSON Format
237
238
The JSON format preserves the complete AST structure including:
239
240
- All node types and their properties
241
- Parent-child relationships
242
- Source code positions (if enabled)
243
- Comments and Javadoc (if enabled)
244
- Type information and metadata
245
246
The serialized JSON is self-contained and can fully reconstruct the original AST structure, making it suitable for long-term storage and cross-platform exchange.