0

My rest API returns something like:

{"UserInfo":[{"userName":"zbradford","firstName":"Zoe","lastName":"Bradford","emailAddress":"ZBradford@ABC.COM"}]}

I would like to let it return only the email address value: ZBradford@ABC.COM

Here is my code:

    import groovy.json.JsonSlurper;

    def slurper = new JsonSlurper()

    def jsonResponse = slurper.parseText(resp)

    jsonResponse.UserInfo.emailAddress.join(',')

I got a java null error, any suggestion on my code? Thanks

dmahapatro
  • 49,365
  • 7
  • 88
  • 117

1 Answers1

2

Has to be a json string to parse.

import groovy.json.JsonSlurper

def str = '{"UserInfo":[{"userName":"zbradford","firstName":"Zoe",
            "lastName":"Bradford","emailAddress":"ZBradford@ABC.COM"}]}'
def slurper = new JsonSlurper().parseText(str)

assert slurper.UserInfo[0].emailAddress == 'ZBradford@ABC.COM'

Have a look here.

Community
  • 1
  • 1
dmahapatro
  • 49,365
  • 7
  • 88
  • 117
  • Hi dmahapatro, thanks for your response. In your answer you used a fixed string, but in reality that string used in the question is a variable returned by the rest API, how do I translate it so it works with other variable outputs? – user2796831 Sep 19 '13 at 19:41
  • @user2796831 Almighty of Java has provided a `toString()` on `Object`. If you apply that to the JsonObject shouldn't you get the json string? – dmahapatro Sep 19 '13 at 20:38