My Groovy is 2.4.0
My code:
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)
The results are as below:
{
"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
My questions are:
- When I println builder2.content, why the content of content99 does not display (it only displays the class something)?
-
When I println builder2.content99, Groovy tells me that:
groovy.lang.MissingPropertyException: No such property: content99 for class: groovy.json.JsonBuilder
-
Even I tried to println builder2.book, Groovy still tells me the same error:
groovy.lang.MissingPropertyException: No such property: book for class: groovy.json.JsonBuilder
How do I read the property in the Json object ?
Thank you.
Best Answer
Because of this method. Since
getContent()
is defined forJsonBuilder
,content
can be called. There's nogetContent99()
method, nor property. You mismatchJsonSlurper
withJsonBuilder
. WithJsonBuilder
it's not possible to refer to a field in such a way.See 1.
In order to refer to fields you need to parse the built document again: