3

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?

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry that was a copy-n-paste bug on my end, please see the updated JSON. Does that change your answer at all?
Cool :-) No, you just need to grab the countries field from the parsed json. Having the variable called countries threw me for a moment... Maybe consider changing the variable name to parsed or something?

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.