使用JsonSlurper映射的Json数组

时间:2019-05-24 03:16:09

标签: json groovy

我想创建一个数据映射,以pid值作为键,名称作为json数组的数组。这是json结构:

{
"measurements": [
    {
        "pid": 6691,
        "name": "lung",
        "measurement": "qualityFactor",
    },
    {
        "pid": 1106,
        "name": "kidney",
        "measurement": "qualityFactor",
    },
    {
        "id": 119,
        "name": "pancreas",
        "measurement": "qualityFactor",
    },

]

}

这是我对Groovy的尝试,但我被困住了:

    def jsonSlurper= new JsonSlurper()
    Object objs=jsonSlurper.parseText(jsonData) 
    List pp =objs.data 
    Map<String,String> m=new HashMap()
    pp.each{ it ->
        it.collect{Map mm ->
            println "Map m is ${mm}"

        }
    }

我希望地图看起来像 [“ 6691”:“肺”,“ 1106”:“肾脏” ....]等

我能做到这一点吗?

1 个答案:

答案 0 :(得分:0)

作为更正后的JSON的完整答案:

def json = '''{
    "measurements": [
        {
            "pid": 6691,
            "name": "lung",
            "measurement": "qualityFactor",
        },
        {
            "pid": 1106,
            "name": "kidney",
            "measurement": "qualityFactor",
        },
        {
            "pid": 119,
            "name": "pancreas",
            "measurement": "qualityFactor",
        }
    ]
}
'''

import groovy.json.*

def parsed = new JsonSlurper().parseText(json)
def map = map.measurements.collectEntries { [it.pid.toString(), it.name] }