json - 使用 Groovy JsonSlurper 解析对象数组

标签 json groovy jsonslurper

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

{
    "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
}

当我运行这段代码时,我得到了 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

我该怎么做才能解决这个问题,以便我可以将数组 JSON 对象解析到我的 sortnamename 变量中?

最佳答案

假设您将 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 重命名为不那么困惑的名称?

关于json - 使用 Groovy JsonSlurper 解析对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444882/

相关文章:

grails - List.retainAll()不能按预期工作(2.3.9版)

java - 一种更优雅的转换方式

json - Groovy比较两个具有未知节点名称和值的json

ios - 使用 JSON 解析指定的 Twitter 提要

php - 使用ajax过滤一些数据后刷新页面时获得相同的内容

java - 从 xml 响应中获取对象

java - Jersey Web 服务和 hibernate 一对多映射

grails - Groovy 字符串匹配 90%(忽略字母大小写)

groovy - JsonSlurper 执行失败