2017-03-07 65 views
1

1.我有一个包含多个地图的列表,如下图所示。 每个地图包含许多键我想获得“名”如何获取子键而不用父键或迭代

{ 
     "question":{ 
      "com.forms.tree":{ 
      "requiredByDefault":true, 
      "questionDetails":{ 
       "com.forms.Details":{ 
        "preferredFormComponent":"TEXT" 
       } 
      }, 
      "locale":{ 
       "language":"en" 
      }, 
      "formField":{ 
       "name":"CUSTOM_347", 
       "tag":"input", 
       "url":"Demo" 
      } 
      } 
     }, 
     "Field":"true" 
    },{ 
    "question":{ 
     "com.forms.tree":{ 
     "questionDetails":{ 
      "com.forms.Details":{ 
       "preferredFormComponent":"TEXT" 
      } 
     }, 
     "locale":{ 
      "language":"en" 
     }, 
     "formField":{ 
      "name":"CUSTOM_348", 
      "url":"Demo" 
     } 
     } 
    }, 
    "Field":"true"} 

我想这属于每一个地图,但不想重复像question?."com.forms.tree"?.formField?.name“名”的价值的价值。

Is there any other approach in groovy? 
+0

有你想找到只只有一个值?或者Json中可能有2个'name'元素? –

+0

我想要所有“名称”属于“formField”的值。 –

+0

json中可能有多个'formField'吗? –

回答

1

所以给出的JSON:

def jsonTxt = '''{ 
    "question":{ 
     "com.forms.tree":{ 
     "requiredByDefault":true, 
     "questionDetails":{ 
      "com.forms.Details":{ 
       "preferredFormComponent":"TEXT" 
      } 
     }, 
     "locale":{ 
      "name": "test", 
      "language":"en" 
     }, 
     "formField":{ 
      "name":"CUSTOM_347", 
      "tag":"input", 
      "url":"Demo" 
     } 
     } 
    }, 
    "Field":"true" 
}''' 

我们可以分析它:

import groovy.json.* 

def json = new JsonSlurper().parseText(jsonTxt) 

你想找到该对象的"formField"项,所以让我们写一个递归搜索器,将走出地图寻找与给定的关键字的第一个条目:

static findFirstByKey(Map map, key) { 
    map.get(key) ?: map.findResult { k, v -> if(v in Map) findFirstByKey(v, key) } 
} 

然后你可以检查它的工作原理:

assert findFirstByKey(json, 'formField')?.name == "CUSTOM_347" 
+0

根据我的问题,jsonTxt是包含多个map的列表。我想我会得到解析错误。 –

+0

多个地图或多个json字符串? –

+0

@tim_yates:输入类型看起来像'List ',这意味着'findFirstByKey'的入口点将会因CCE而失败。 – aalmiray