1

I am new to groovy and need to parse JSON response. the response looks like this:

[
    {
        "name": "John",
        "start_date": "2016-09-30",
        "sort_order": 1
    },
    {
        "name": "Tony",
        "start_date": "2016-06-30",
        "sort_order": 2
    }
]

How can I get each object from that? would like to end up with name, start_date and sort_order for each student together.

1 Answer 1

4

You would use JsonSlurper

import groovy.json.*

def json = '''[ 
    { "name": "John", "start_date": "2016-09-30", "sort_order": 1 },
    { "name": "Tony", "start_date": "2016-06-30", "sort_order": 2 } ]'''

def parsed = new JsonSlurper().parseText(json)

assert parsed.name == ['John', 'Tony']
Sign up to request clarification or add additional context in comments.

3 Comments

To get what you're asking for Punter do this, but it would be parsed.each { println it } that should get you what you want.
Thanks for the response but I should have been a little more clearer on what outcome i want, which is to print total object count and then to have print each object. i.e. total students= 2, student 1 is (name = john, start_date = 2016-09-30), student 2 is (name = Tony, start_date = 2016-06-30) according to the sort order
Added this bit to get what i want. Thanks tim_yates and dataman. for (item in parsed){ def name = item.name def startDate = item.start_date def sortOrder = item.sort_order println "name is : " + name println "startDate is : " + startDate println "sortOrder is : " + sortOrder }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.