2017-03-21 37 views
0

我试图做一个JSON对象(从根到叶节点),并使用JSONObject和JSONArray类在groovy中从我的孩子兄弟姐妹树结构递归地以json格式打印但我不断地得到这个“无法解决类JSONObject”的错误。我的代码片段如下:如何在Groovy中使用JSONObject和JSONArray类?没有得到“无法解决类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

使用正确的导入,并且如果JSONObject类来自ext lib,请首先使用@Grab来获取依赖项。 –

+0

@tim_yates是, –

回答

0

因此,考虑到:

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 
       } 
      ] 
     } 
    ] 
} 
+0

非常感谢,tim_yates。这是完美的答案。 –

相关问题