我有这段代码:
"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('&','\",\"') + "\"}"
它返回有效的json格式,虽然我想从我尝试过的字符串中获取特定值:
println converted.responsetext.toString()
它有一个错误说
没有这样的属性:class的responsetext:java.lang.String
答案 0 :(得分:0)
您可以将请求参数转换为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"