我的Groovy是2.4.0
我的代码:
def builder2 = new JsonBuilder()
builder2.book {
isbn '0321774094'
title 'Scala for the Impatient'
author (['Cay S. Horstmann', 'Hellen'])
publisher 'Addison-Wesley Professional'
content99 {
contentType '1'
text 'Hello'
}
}
println(builder2.toPrettyString())
println(builder2.content)
println(builder2.content99)
println(builder2.book)
结果如下:
{
"book": {
"isbn": "0321774094",
"title": "Scala for the Impatient",
"author": [
"Cay S. Horstmann",
"Hellen"
],
"publisher": "Addison-Wesley Professional",
"content99": {
"contentType": "1",
"text": "Hello"
}
}
}
[book:[isbn:0321774094, title:Scala for the Impatient, author:[Cay S. Horstmann, Hellen], publisher:Addison-Wesley Professional, content99:TestJson$_testJson_closure1$_closure2@38ee79e5]]
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: content99 for class: groovy.json.JsonBuilder
Groovy.lang.MissingPropertyException: No such property: book for class: groovy.json.JsonBuilder
我的问题是:
当我打印builder2.content99时,Groovy告诉我:
groovy.lang.MissingPropertyException:没有这样的属性:class99的内容:groovy.json.JsonBuilder
即使我尝试println builder2.book,Groovy仍然告诉我同样的错误:
groovy.lang.MissingPropertyException:没有这样的属性:book for class:groovy.json.JsonBuilder
如何读取Json对象中的属性?
谢谢。
答案 0 :(得分:2)
由于这个method。由于为getContent()
定义了JsonBuilder
,因此可以调用content
。没有getContent99()
方法,也没有属性。您与JsonSlurper
不匹配JsonBuilder
。使用JsonBuilder
时,无法以这种方式引用字段。
见1.
要引用您需要再次解析构建文档的字段:
import groovy.json.*
def builder2 = new JsonBuilder()
builder2.book {
isbn '0321774094'
title 'Scala for the Impatient'
author (['Cay S. Horstmann', 'Hellen'])
publisher 'Addison-Wesley Professional'
content99 {
contentType '1'
text 'Hello'
}
}
def pretty = builder2.toPrettyString()
println(pretty)
println(builder2.content)
def slurped = new JsonSlurper().parseText(pretty)
println(slurped.book.content99)
println(slurped.book)