Groovy web console

subscribe to the feed Subscribe
to this
site
JsonBuilder Example (via #groovywebconsole)
tweet this snippet Tweet
this
script

JsonBuilder Example

Published 2 years ago by Evgeny Goldin with tags json builders markup
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
@groovy.transform.Canonical
class Message {
    long   id
    String sender
    String text
}
 
assert 'Message(23, me, some text)' ==
       new Message( 23, 'me', 'some text' ).toString()


def messages = [ new Message( 23, 'me', 'some text'       ),
                 new Message( 24, 'me', 'some other text' ),
                 new Message( 25, 'me', 'same text'       )]
 

def writer = new StringWriter()
def xml    = new groovy.xml.MarkupBuilder( writer )
 
xml.messages() {
    messages.each { Message m -> message( id     : m.id,
                                          sender : m.sender,
                                          text   : m.text )}
}
 
assert writer.toString() == """
<messages>
  <message id='23' sender='me' text='some text' />
  <message id='24' sender='me' text='some other text' />
  <message id='25' sender='me' text='same text' />
</messages>""".trim()


def json = new groovy.json.JsonBuilder()
 
json.messages() {
    messages.each { Message m -> message( id     : m.id,
                                          sender : m.sender,
                                          text   : m.text )}
}
 
assert json.toString() ==
       '{"messages":{"message":{"id":25,"sender":"me","text":"same text"}}}'


json = new groovy.json.JsonBuilder()
 
json.messages() {
    message {
        id     23
        sender 'me'
        text   'some text'
    }
    message {
        id     24
        sender 'me'
        text   'some other text'
    }
}
 
assert json.toString() ==
       '{"messages":{"message":{"id":24,"sender":"me","text":"some other text"}}}'


def listOfMaps = messages.collect{
                 Message m -> [ id     : m.id,
                                sender : m.sender,
                                text   : m.text ]}
 
assert new groovy.json.JsonBuilder( listOfMaps ).toString() ==
       '''[{"id":23,"sender":"me","text":"some text"},
           {"id":24,"sender":"me","text":"some other text"},
           {"id":25,"sender":"me","text":"same text"}]'''.
       readLines()*.trim().join()