简体   繁体   English

groovy从字符串中提取值

[英]groovy extract value from string

I got a string from a server response: 我从服务器响应中得到了一个字符串:

responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"

then I do: 然后我做:

responseString[1..-2].tokenize(',')

got: 得到:

[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]

get(3) got: get(3)得到了:

""userid":"user_1""

what I need is the user_1, is there anyway I can actually get it? 我需要的是user_1,反正我真的可以得到它吗? I have been stuck here, other json methods get similar result, how to remove the outside ""? 我被困在这里,其他json方法也得到类似的结果,如何删除外面的“”?

Thanks. 谢谢。

If you pull out the proper JSON from responseStr , then you can use JsonSlurper , as shown below: 如果从responseStr提取正确的JSON,则可以使用JsonSlurper ,如下所示:

def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'

def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]

import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" ==  json.userid

This code can help you get you to the userid. 此代码可以帮助您获得用户ID。

def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]

this pattern can help you getting any of the values you want from the string. 此模式可以帮助您从字符串中获取所需的任何值。 Try replacing userid with age, you will get that 尝试将用户ID替换为年龄,您将获得

def match = (str=~ /"age":"(.*?)"/)

@Michael code is also correct. @Michael代码也是正确的。 Its just that you have clarified that you want the user Name to be specific 只是您已经澄清了您想要特定的用户名

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

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