Angelina
Angelina

Reputation: 2265

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?

Upvotes: 0

Views: 2510

Answers (2)

ernest_k
ernest_k

Reputation: 45339

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"
                    ]
                ]
            ]
        ]
    ]]
)

Upvotes: 1

kaweesha
kaweesha

Reputation: 803

  1. If you are creating a JSON from Groovy objects, then you can use; JsonOutput

  2. And if you have several values to pass and create a JSON object, then you can use; JsonGenerator

  3. Or you can use JsonBuilder or StreamingJsonBuilder

check the groovy documentation

Upvotes: 1

Related Questions