对象为JsonBuilder()在Groovy中构建的Json

时间:2015-03-31 09:14:49

标签: json groovy properties jsonbuilder

我的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

我的问题是:

  1. 当我打印builder2.content时,为什么不显示content99的内容(它只显示类的东西)?
  2. 当我打印builder2.content99时,Groovy告诉我:

    groovy.lang.MissingPropertyException:没有这样的属性:class99的内容:groovy.json.JsonBuilder

  3. 即使我尝试println builder2.book,Groovy仍然告诉我同样的错误:

    groovy.lang.MissingPropertyException:没有这样的属性:book for class:groovy.json.JsonBuilder

  4. 如何读取Json对象中的属性?

    谢谢。

1 个答案:

答案 0 :(得分:2)

  1. 由于这个method。由于为getContent()定义了JsonBuilder,因此可以调用content。没有getContent99()方法,也没有属性。您与JsonSlurper不匹配JsonBuilder。使用JsonBuilder时,无法以这种方式引用字段。

  2. 见1.

  3. 要引用您需要再次解析构建文档的字段:

    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)