groovyjsonbuilder

Generate JSON object in Groovy


For some reason I am not able to create JSON object in Groovy using JSONBuilder

Here is what I have but it comes back {}:

import groovy.json.JsonBuilder

JsonBuilder builder = new JsonBuilder()
    builder {
        name "Name"
        description "Description"
        type "schedule type"
        schedule {
          recurrenceType "one time"
          start "${startDateTime}"
          end "${endDateTime}"
        }
        scope {
          entities ["${applicationId}"]
          matches [
            {
              tags [
                {
                  key "key name"
                  context "some context"
                }
              ]
            }
          ]
        }
      }

Does anyone know a simple way to create JSON object with nested elements?


Solution

  • I tend to find JsonOutput to be simpler to use for data that is already constructed. Yours would look like this:

    groovy.json.JsonOutput.toJson(
       [name: "Name",
        description: "Description",
        type: "schedule type",
        schedule: [
            recurrenceType: "one time",
            start: "${startDateTime}",
            end: "${endDateTime}"
        ],
        scope: [
            entities: ["${applicationId}"],
            matches: [
                [
                    tags: [
                        [
                            key: "key name",
                            context: "some context"
                        ]
                    ]
                ]
            ]
        ]]
    )