Using Groovy JsonSlurper to parse an array of objects

smeeb picture smeeb · Mar 23, 2018 · Viewed 8.2k times · Source

Groovy here. I am parsing a file that contains a list of all the countries:

{
    "countries": [
      {
        "id": "1",
        "sortname": "AF",
        "name": "Afghanistan"
      },
      {
         "id": "2",
         "sortname": "AL",
         "name": "Albania"
      },
      ...
    ]
}

I am trying to read each country into a parseable object that I can then process in my code:

String countriesJson = new File(classLoader.getResource('countries.json').getFile()).text
def countries = new JsonSlurper().parseText(countriesJson)

countries.each { country ->
    String sortname = country.sortname
    String name = country.name

    // do something with all this info and then move on to the next country
}

When I run this code I get MissingPropertyExceptions:

Exception in thread "main" groovy.lang.MissingPropertyException: No such property: sortname for class: java.util.LinkedHashMap$Entry
        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:53)
        at org.codehaus.groovy.runtime.callsite.GetEffectivePojoPropertySite.getProperty(GetEffectivePojoPropertySite.java:66)
        at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callGetProperty(AbstractCallSite.java:296)
        ...rest of stacktrace omitted for brevity

What can I do to fix this so that I can parse the array JSON objects into my sortname and name variables?

Answer

tim_yates picture tim_yates · Mar 23, 2018

Assuming you have your json wrapped in { ... } so it's valid (unlike in the question), you need to get the countries object first.

so:

countries.countries.each { country ->
    String sortname = country.sortname
    String name = country.name

    // do something with all this info and then move on to the next country
}

Maybe rename the variable countries to something less confusing?