0

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?

Angelina
  • 2,175
  • 10
  • 42
  • 82
  • 1
    Why not something like `groovy.json.JsonOutput.toJson([name:'Name', description: 'Description', schedule:[recurrenceType:'one time']])`? The parameter is just a map with all the data. – ernest_k May 20 '20 at 04:53
  • @ernest_k I tried your suggestion. I think at this point, I tried any variation :/ my IDE complains if I add commas, like in your suggestion, so I didn't add them, yet it returns {} did you test your suggestion ? Does it work for you? return JsonOutput.toJson({name: "Name" description: "Description" ...}).toString() – Angelina May 20 '20 at 04:59
  • 1
    What you have there is not what I suggested. I suggested a map parameter (`[... : ...]`, not `{}`). Yes, I tested it, it produced the string `{"name":"Name","description":"Description","schedule":{"recurrenceType":"one time"}}` – ernest_k May 20 '20 at 05:00
  • @ernest_k I good one. Almost there. How would I treat matches and tags that also need [ ] in the output? "matches": [ { "tags": [ { key "key name" context "some context" } ] } ] double them? – Angelina May 20 '20 at 05:09
  • 1
    I'll add an answer for you. – ernest_k May 20 '20 at 05:10

2 Answers2

1
  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

kaweesha
  • 803
  • 6
  • 16
1

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"
                    ]
                ]
            ]
        ]
    ]]
)
ernest_k
  • 44,416
  • 5
  • 53
  • 99