Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example code of how NOT to use redundant Map whenr generating ast tree JSON
public static String toJson(DetailAST ast) throws IOException {
int nodeId = ROOT_NODE_ID;
Stack<Integer> parentNodeIdStack = new Stack<>();
parentNodeIdStack.push(nodeId); // root node id
DetailAST currentNode = ast;
StringWriter writer = new StringWriter();
JsonGenerator jsonGenerator = JSON_FACTORY.createJsonGenerator(writer).useDefaultPrettyPrinter();
jsonGenerator.writeStartObject();
while (currentNode != null) {
DetailAST toVisit = currentNode.getFirstChild();
nodeId++;
jsonGenerator.writeObjectFieldStart(currentNode.toString());
jsonGenerator.writeStringField("text", currentNode.getText());
jsonGenerator.writeStringField("type", TokenTypes.getTokenName(currentNode.getType()));
jsonGenerator.writeNumberField("lineNo", currentNode.getLineNo());
jsonGenerator.writeNumberField("columnNo", currentNode.getColumnNo());
jsonGenerator.writeNumberField("id", nodeId);
jsonGenerator.writeNumberField("parentId", parentNodeIdStack.peek());
jsonGenerator.writeEndObject();
if (toVisit != null) {
parentNodeIdStack.push(nodeId);
}
while ((currentNode != null) && (toVisit == null)) {
toVisit = currentNode.getNextSibling();
if (toVisit == null) {
currentNode = currentNode.getParent();
parentNodeIdStack.pop();
}
}
currentNode = toVisit;
}
jsonGenerator.writeEndObject();
jsonGenerator.close();
String result = writer.toString();
writer.close();
parentNodeIdStack = null;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.