0

I want to parse a nested JSON structure in Groovy. I would like to parse a sub element structure and then return the string in JSON format.

The Nested JSON structure:

{
    "username": "test",
    "token": "test1",
    "url": "http://www.abc.to",
    "testsession":
    {
        "serverName": "0.0.0.0",
        "serverPort": 22,
        "remoteUsername": "admin",
        "remotePassword": "admin"
    },
    "deviceapp":
    {
        "repo": "abc-mvn-a-test-local",
        "path": "com/test\/test2\/test3\/mob",
        "platform": "ANDROID"
    }
}

my code below using JSONSlurper isn't quite giving me what i want:

def slurper = new JsonSlurper().parseText(json)
String deviceAppParsed = slurper.deviceapp
println "deviceAppParsed " + deviceAppParsed
// returns deviceAppParsed {repo=oxp-mvn-a-rel-local, path=com/nagra/opentv/experience/mob, platform=ANDROID}
def jsonDeviceApp = JsonOutput.toJson(deviceAppParsed)
println "IS IT JSON? " + jsonDeviceApp
// returns IS IT JSON "{repo=oxp-mvn-a-rel-local, path=com/nagra/opentv/experience/mob, platform=ANDROID}"

How can i parse the json to retrieve the nested deviceapp structure in raw JSON? Thanks.

: def slurper = new JsonSlurper().parseText(json) String deviceAppParsed = slurper.deviceapp def jsonDeviceApp = JsonOutput.toJson(deviceAppParsed)

I expected println jsonDeviceApp to return:

{"repo": "abc-mvn-a-test-local","path": "com/test\/test2\/test3\/mob","platform": "ANDROID"}

instead it returned:

"{repo=oxp-mvn-a-rel-local, path=com/nagra/opentv/experience/mob, platform=ANDROID}"
1
  • Please be more specific than "isn't quite giving me what i want". Show the results you are getting, the results that you expect, and what you've tried to explain the difference. Commented Jan 31, 2020 at 17:28

1 Answer 1

1

just replace String to def in the following line:

String deviceAppParsed = slurper.deviceapp

by using string you are converting Object returned by slurper.deviceapp to string

should be:

def deviceAppParsed = slurper.deviceapp

in this case last line will print json

{"repo":"abc-mvn-a-test-local","path":"com/test/test2/test3/mob","platform":"ANDROID"}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.