简体   繁体   中英

How to get a value from a JSON (string) in Groovy

I have been struggling to figure out how to get a parameter out of a JSON string in Groovy.

I have a string similar to:

'{"id":"12345678","name":"Sharon","email":"sharon\u0040example.com"}'

and am trying to extract the email address.

I can of course use regex, or other substring methods, but I'm sure there is a cleaner way.

Use JsonSlurper .

import groovy.json.JsonSlurper

def str = '{"id":"12345678","name":"Sharon","email":"sharon\u0040example.com"}'
def slurper = new JsonSlurper().parseText(str)

assert slurper.email == 'sharon@example.com'
assert slurper.name  == 'Sharon'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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