如何从转换后的字符串中获取值

How do I get Value from a converted String

我有这个代码:

"response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"

我尝试使用以下代码将其转换为 json 格式:

def converted = "{\"" + resp.data.toString()
                                .replaceAll('=','\":\"')
                                .replaceAll('&','\",\"') + "\"}"

它 returns 有效的 json 格式,尽管我想从我尝试做的那个字符串中获取特定值:

println converted.responsetext.toString()

它有一个错误说

没有这样的 属性:class 的响应文本:java.lang.String

您可以将请求参数转换为 Map,如果需要,还可以转换为 json 字符串,如下所示:

String str = "response=3&responsetext=Duplicate transaction REFID:3154223053&authcode=&transactionid=&avsresponse=&cvvresponse=&orderid=&type=auth&response_code=300"

def map = str.tokenize(/&/).collectEntries { 
    def entity = it.tokenize(/=/)
    [ entity[0], entity[1] ]
}

assert map.responsetext == "Duplicate transaction REFID:3154223053"

// Json
println new groovy.json.JsonBuilder( map ).toPrettyString()

如果你想从你现在拥有的东西继续前进,那么下面的实现就足够了:

def items = new groovy.json.JsonSlurper().parseText( converted )
assert items.responsetext == "Duplicate transaction REFID:3154223053"