Created
November 30, 2014 16:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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