这里太棒了。我正在解析一个包含所有国家列表的文件:
{
"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 和变量中,我可以做些什么来解决这个问题呢?
发布于 2018-03-23 08:02:26
假设您的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重命名为不那么让人困惑的东西?
https://stackoverflow.com/questions/49444882
复制相似问题