简体   繁体   English

将groovy字符串转换为groovy中的地图

[英]Convert a groovy string to a map in groovy

I need to convert a groovy string to a map object. 我需要将groovy字符串转换为map对象。 The string exactly is : 字符串恰好是:

"\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""

I need to fetch the value corresponding to "name". 我需要获取与“名称”相对应的值。 I have tried using the JsonBuilder, JsonSlurper and regexp approach for this problem. 我曾尝试使用JsonBuilder,JsonSlurper和regexp方法解决此问题。 But I have not yet come to a solution. 但是我还没有解决。

For Simplifying things I have removed the backslashes with : replaceAll .The reduced string is : 为了简化起见,我用: replaceAll删除了反斜杠。减少的字符串是:

""{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}""

Looking forward to any help on this.I am using grails 2.5.1 and groovy 2.4.10. 期待对此有任何帮助。我正在使用grails 2.5.1和groovy 2.4.10。

You have a json string which can be parsed with JsonSlurper . 您有一个可以用JsonSlurper解析的json字符串。

Here you go: 干得好:

def string = """{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}"""
def json = new groovy.json.JsonSlurper().parseText(string)
assert json instanceof Map​​​​​

You may quickly try this online Demo 您可以快速尝试此在线演示

/*

i put exactly this string into the file 1.gr
"\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""

*/

def s= new File("./1.gr").text
println s 
// output> "\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""
s=Eval.me(s)
println s 
// output> "{\"1\":[],\"2\":[],\"3\":[{\"name\":\"PVR_Test_Product\",\"id\":\"100048\"}],\"4\":[],\"5\":[]}"
s=Eval.me(s)
println s 
// output> {"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}

//now it's possible to parse json
def json = new groovy.json.JsonSlurper().parseText(s)

Someone is handing you down the JSON of the JSON of your data. 有人将您的数据传递给JSON。 Blindly removing the \\ might end up badly. 盲目删除\\可能会导致严重后果。 But you can just de-JSON twice. 但是,您可以只对JSON进行两次去JSON。

As always in such cases: if someone is giving you data in that shape you can talk to, make sure, they have a perfectly fine reason to do such things. 在这种情况下,一如既往:如果某人以您可以与之交谈的形式给您提供数据,请确保他们有做这些事情的充分理由。 More often than not, this some sort of error. 通常,这是某种错误。

def jsonOfJson = "\"{\\\"1\\\":[],\\\"2\\\":[],\\\"3\\\":[{\\\"name\\\":\\\"PVR_Test_Product\\\",\\\"id\\\":\\\"100048\\\"}],\\\"4\\\":[],\\\"5\\\":[]}\""
def slurper = new groovy.json.JsonSlurper()
def json = slurper.parseText(jsonOfJson)
println(json.inspect())
// -> '{"1":[],"2":[],"3":[{"name":"PVR_Test_Product","id":"100048"}],"4":[],"5":[]}'
def data = slurper.parseText(json)
println(data.inspect())
// -> ['1':[], '2':[], '3':[['name':'PVR_Test_Product', 'id':'100048']], '4':[], '5':[]]
assert data["3"].size()==1

The code below converts the JSON like string to an object or an array: 下面的代码将JSON之类的字符串转换为对象或数组:

#!/usr/bin/env groovy

/**
 * Get the nearest object or array end
 */
def getNearestEnd(String json, int start, String head, String tail) {
    def end = start
    def count = 1
    while (count > 0) {
        end++
        def c = json.charAt(end)
        if (c == head) {
            count++
        } else if (c == tail) {
            count--
        }
    }
    return end;
}

/**
 * Parse the object
 */
def parseObject(String json) {
    def map = [:]
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    def key = ''
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                if (state == 'none') {
                    def keyStart = index + 1;
                    def keyEnd = keyStart;
                    while (json.charAt(keyEnd) != '"') {
                        keyEnd++
                    }
                    index = keyEnd
                    def keyValue = json[keyStart .. keyEnd - 1]
                    key = keyValue
                } else if (state == 'value') {
                    def stringStart = index + 1;
                    def stringEnd = stringStart;
                    while (json.charAt(stringEnd) != '"') {
                        stringEnd++
                    }
                    index = stringEnd
                    def stringValue = json[stringStart .. stringEnd - 1]
                    map.put(key, stringValue)
                }
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd json, index, '{', '}'
                def objectValue = json[objectStart .. objectEnd]
                map.put(key, parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                map.put(key, parseArray(arrayValue))
                index = arrayEnd
                break

            case ':':
                state = 'value'
                break

            case ',':
                state = 'none'
                key = ''
                break;

            case ["\n", "\t", "\r", " "]:
                break

            default:
                break
        }
        index++
    }

    return map
}

/**
 * Parse the array
 */
def parseArray(String json) {
    def list = []
    def length = json.length()
    def index = 1
    def state = 'none' // none, string-value, other-value
    while (index < length -1) {
        def c = json.charAt(index)
        switch(c) {
            case '"':
                def stringStart = index + 1;
                def stringEnd = stringStart;
                while (json.charAt(stringEnd) != '"') {
                    stringEnd++
                }
                def stringValue = json[stringStart .. stringEnd - 1]
                list.add(stringValue)
                index = stringEnd
                break

            case '{':
                def objectStart = index
                def objectEnd = getNearestEnd(json, index, '{', '}')
                def objectValue = json[objectStart .. objectEnd]
                list.add(parseObject(objectValue))
                index = objectEnd
                break

            case '[':
                def arrayStart = index
                def arrayEnd = getNearestEnd(json, index, '[', ']')
                def arrayValue = json[arrayStart .. arrayEnd]
                list.add(parseArray(arrayValue))
                index = arrayEnd
                break

            case ["\n", "\t", "\r", " "]:
                break

            case ',':
                state = 'none'
                key = ''
                break;

            default:
                break
        }
        index++
    }

    return list
}

/**
 * Parse the JSON, object or array
 */
def parseJson(String json) {
    def start = json[0]
    if (start == '[') {
        return parseArray(json)
    } else if (start == '{') {
        return parseObject(json)
    } else {
        return null
    }
}

// Test code
println parseJson('{"abdef":["Jim","Tom","Sam",["XYZ","ABC"]],{"namek":["adbc","cdef"]}}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM