Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JSONObject and JSONArray class in groovy? without getting "unable to resolve class JSONObject" error on terminal

Tags:

json

groovy

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());
    }
}
like image 409
Suraj Sharma Avatar asked Oct 29 '22 10:10

Suraj Sharma


1 Answers

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
                }
            ]
        }
    ]
}
like image 176
tim_yates Avatar answered Nov 15 '22 06:11

tim_yates