如何在groovy中使用JSONObject和JSONArray类?没有在终端上“无法解析类JSONObject”错误

时间:2017-03-21 11:30:27

标签: json groovy

我正在尝试创建一个json对象(从root到leaf节点)并使用JSONObject和JSONArray类从groovy中的child-sibling树结构以递归方式打印json格式,但我不断得到这个“无法解析类JSONObject “错误。我的代码段如下:

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());
    }
}

1 个答案:

答案 0 :(得分:1)

所以,给定:

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')
    ])
])

我可以这样做:

import groovy.json.*

println new JsonBuilder(tree).toPrettyString()

要打印出来:

{
    "category": "a",
    "children": [
        {
            "category": "ab",
            "children": null
        },
        {
            "category": "ad",
            "children": [
                {
                    "category": "ada",
                    "children": null
                }
            ]
        }
    ]
}