how to convert json into key value pair completely using groovy

…衆ロ難τιáo~ 提交于 2019-12-12 06:05:46

问题


i m trying to convert json into map as key value pair i have a method JsonSlurper() which give me the key value pair but my query is i have a json as bellow.

{"Result":"null",
"gbet":{"Qpet":[
{"msg":"MSG","over":"N","repair":[{"notification":null,"sce":"1","repair1":"CA","repairDes":null,"ran":1},
{"rep":"dvr"}],
{"msgger":"MSGwe","overw":"Ner"}]
}

how to get all the things in a single map with each key value pair i m doing like this

 def slurper = new JsonSlurper().parseText(str)

    log.info("sulpher"+slurper)
    def keys=slurper.keySet();
    log.info('keys'+keys)

but its not working for me i want each key and value pair as a separate field.


回答1:


According to the JSON String you provided; It has only two parent keys i.e. Result and gbet. Where gbet has other nodes within it. You will have to fix your string or write you own method to flatten the string. There is no out of the box functionality available to achieve what you are asking for.




回答2:


You will have to implement your own flatten method. For example:

Map flattenMap(Map json) {
def result = [:]
json.each { k, v ->
    if (v instanceof Map) {
        result << flattenMap(v)
    } else if (v instanceof Collection && v.every {it instanceof Map}) {
        v.each { result << flattenMap(it) }
    } else {
        result[k] = v
    }
}
result
}

This example is using recursion so if it is nested too deeply it will overflow. It will not work on your sample because it is not valid json.



来源:https://stackoverflow.com/questions/29072556/how-to-convert-json-into-key-value-pair-completely-using-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!