Skip to content

Instantly share code, notes, and snippets.

@daniilyar
Created November 30, 2014 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daniilyar/cf07a850939970ddde74 to your computer and use it in GitHub Desktop.
Save daniilyar/cf07a850939970ddde74 to your computer and use it in GitHub Desktop.
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