【问题标题】:Using Groovy JsonSlurper to parse an array of objects使用 Groovy JsonSlurper 解析对象数组
【发布时间】:2018-03-23 07:58:10
【问题描述】:

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

{
    "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 对象解析为我的 sortname 和 name 变量?

【问题讨论】:

    标签: json groovy jsonslurper


    【解决方案1】:

    假设您的 json 包含在 { ... } 中,因此它是有效的(与问题不同),您需要先获取国家/地区对象。

    所以:

    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。这会改变你的答案吗?
    • 酷 :-) 不,您只需要从解析的 json 中获取 countries 字段。有一个名为 countries 的变量让我愣了一下......也许考虑将变量名称更改为 parsed 或其他什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多