使用Groovy JsonSlurper解析对象数组

时间:2018-03-23 07:58:10

标签: json groovy jsonslurper

Groovy在这里。我正在解析一个包含所有国家/地区列表的文件:

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

我正在尝试将每个国家/地区读入一个可解析的对象,然后我可以在我的代码中处理它:

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
}

当我运行此代码时,我得到MissingPropertyException s:

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

我可以做些什么来解决这个问题,以便将数组JSON对象解析为sortnamename变量?

1 个答案:

答案 0 :(得分:1)

假设你的json包含在{ ... }中,因此它有效(与问题不同),你需要首先获得countries对象。

这样:

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
}

也许将变量countries重命名为不那么令人困惑的东西?