2017-12-18 263 views
0

我想从一个json的关键名是“label”并且想要存储在一个列表中获取所有的值。 我的问题是,标签键的位置不固定。有时它在子节点下有时在父节点下,有时在子节点下到子节点。我们可以在常规中使用递归闭包,但我不知道如何?groovy json中的递归闭包

的Json ::

[ 
    { 
    { 
     "id": "2", 
     "label": "NameWhatever" 
    }, 
    { 
     "id": "123", 
     "name": "Some Parent Element", 
     "children": [{ 
       "id": "123123", 
       "label": "NameWhatever" 
      }, 
      { 
       "id": "123123123", 
       "name": "Element with Additional Children", 
       "children": [{ 
         "id": "123123123", 
         "label": "WhateverChildName" 
        }, 
        { 
         "id": "12112", 
         "name": "Element with Additional Children", 
         "children": [{ 
           "id": "123123123", 
           "label": "WhateverChildName" 
          }, 
          { 
           "id": "12112", 
           "name": "Element with Additional Children", 
           "children": [{ 
             "id": "12318123", 
             "label": "WhateverChildName" 
            }, 
            { 
             "id": "12112", 
             "label": "NameToMap" 
            } 
           ] 
          } 
         ] 
        } 
       ] 
      } 
     ] 
    } 
] 

回答

1

基于similar question

import groovy.json.JsonSlurper 

def mapOrCollection (def it) { 
    it instanceof Map || it instanceof Collection 
} 

def findDeep(def tree, String key, def collector) { 
    switch (tree) { 
     case Map: return tree.each { k, v -> 
      mapOrCollection(v) 
      ? findDeep(v, key, collector) 
       : k == key 
       ? collector.add(v) 
        : null 
     } 
     case Collection: return tree.each { e -> 
      mapOrCollection(e) 
       ? findDeep(e, key, collector) 
       : null 
     } 
     default: return null 
    } 
} 

def collector = [] 
def found = findDeep(new JsonSlurper().parseText(json), 'label', collector) 
println collector 

假设变量json含有问题,打印给定的输入JSON:

[NameWhatever, NameWhatever, WhateverChildName, WhateverChildName, WhateverChildName, NameToMap]