RredCat
RredCat

Reputation: 5421

Groovy JSON array builder with custom members inside of closure

I am going to create simple JSON array from my items list. I have found great sample how to do it with JsonBuilder. It looks like:

class Author {
      String name
 }
 def authors = [new Author (name: "Guillaume"),
            new Author (name: "Jochen"),
            new Author (name: "Paul")]

 def json = new groovy.json.JsonBuilder()
 json authors, { Author author ->
      name author.name
 }

But, I have to add a custom property to my JSON. It has to look like:

 json authors, { Author author ->
      def c = author.name.bytes.encodeBase64()
      name author.name
      code c
 }

But this code isn't working, I have to separate in JSON members and closure members in some way. Frankly, I am not a big expert in groovy and guess that answer could be a bit simple.

Also, I know that I can create the custom list of my items and convert this list in a next way:

def json = new groovy.json.JsonBuilder(authors)

But, I want to implement this in the closure.

Upvotes: 0

Views: 831

Answers (2)

Vampire
Vampire

Reputation: 38649

The code you suggest produces [[name:Guillaume, code:R3VpbGxhdW1l], [name:Jochen, code:Sm9jaGVu], [name:Paul, code:UGF1bA==]], so your code is just fine? It seems your environment is blocking this script.

Upvotes: 1

Will
Will

Reputation: 14529

You can create the base64 string using a GString:

import groovy.json.JsonBuilder

def json(items) {
    def builder = new JsonBuilder()

    builder(items.collect { item ->
        [ 
            name: item.name, 
            code: "${item.name.bytes.encodeBase64()}"
        ]
    })
    builder.toString()
}

def authors = [
    [ name: "John Doe" ]
]


assert json(authors) == '[{"name":"John Doe","code":"Sm9obiBEb2U="}]'

Upvotes: 0

Related Questions