对象由JsonBuilder()在Groovy内置
问题描述:
我的Groovy对象JSON是2.4.0对象由JsonBuilder()在Groovy内置
我的代码:
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:[email protected]]]
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
我的问题是:
- 当我println builder2.content,为什么内容content99不显示(它只显示类的东西)?
-
当我调用println builder2.content99,Groovy的告诉我说:
groovy.lang.MissingPropertyException:没有这样的属性:content99类:groovy.json.JsonBuilder
-
即使我试图给println builder2 .book,Groovy的还告诉我同样的错误:
groovy.lang.MissingPropertyException:没有这样的属性:书类:groovy.json.JsonBuilder
如何读取Json对象中的属性?
谢谢。
答
因为这个method。由于
getContent()
定义为JsonBuilder
,因此可以调用content
。没有getContent99()
方法,也没有财产。您与JsonBuilder
不匹配JsonSlurper
。与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)
+0
嗨,欧泊,谢谢。你的答案确实解决了我的问题。 – wureka 2015-04-12 21:41:03
'ISBN” ... '''意味着ISBN(' ...')'而不是'isbn ='...'' – cfrick 2015-03-31 10:12:18