Search code examples
arraysjsongroovyjsonbuilder

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.


Solution

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