Json – object in object for Json built by JsonBuilder() in Groovy

groovyjsonjsonbuilderproperties

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:

  1. When I println builder2.content, why the content of content99 does not display (it only displays the class something)?
  2. When I println builder2.content99, Groovy tells me that:

    groovy.lang.MissingPropertyException: No such property: content99 for class: groovy.json.JsonBuilder

  3. 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

  1. Because of this method. Since getContent() is defined for JsonBuilder, content can be called. There's no getContent99() method, nor property. You mismatch JsonSlurper with JsonBuilder. With JsonBuilder it's not possible to refer to a field in such a way.

  2. See 1.

  3. In order to refer to fields you need to parse the built document again:

    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)