I am trying to make a json object(from root to leaf node) and print in json format recursively from my child-sibling tree structure in groovy using JSONObject and JSONArray class but I am continously getting this "unable to resolve class JSONObject" error . My code snippet is below :
void screenout(Nope roota, Map mapp) {
me = roota;
Nope temp = roota;
if (roota == null)
return;
def rootie = new JSONObject();
def infos = new JSONArray();
while (temp != null) {
def info = new JSONObject();
info.put("category", temp.val)
info.put("path", mapp[temp.val])
infos.add(info);
roota = temp;
temp = temp.sibling;
screenout(roota.child, mapp);
}
rootie.put("children", infos);
if (me == root) {
println(rootie.JSONString());
}
}
So, given:
class Node {
String category
List children
}
def tree = new Node(category:'a', children:[
new Node(category:'ab'),
new Node(category:'ad', children:[
new Node(category:'ada')
])
])
I can just do:
import groovy.json.*
println new JsonBuilder(tree).toPrettyString()
To print out:
{
"category": "a",
"children": [
{
"category": "ab",
"children": null
},
{
"category": "ad",
"children": [
{
"category": "ada",
"children": null
}
]
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With