3

I have some data in Groovy's objects which I need to convert to a JSON string array. The final result should be..

 [
      {
        "keys":{
                 "passcode": "12345"
               },
        "values":{
                  "EmailAddress": "[email protected]",
                  "message": "Hello, is it me you are looking for?"
                 }
      }
 ]

I found this post but the accepted answer which uses JSON Builder didn't make sense and the second answer using JSON converter didn't work...

def deJson = [
            keys: [
                    passcode: secretCode
            ],
            values: [
                    EmailAddress:emailData.to[0],
                    message: content.message
            ]
    ] as grails.converters.JSON

This created a JSON object when I needed an array.

Can anyone suggest how I can use JSON Builder or JSON converter to create an array string like I have above?

1 Answer 1

3

JSON is specific to Grails (as mentioned in one of the comments in the answer from the previous post). You should have followed the question itself in the post, that has the answer.

Using groovy.json.JsonBuilder, the expected way to serialize would be:

def jsonObj = [
    keys: [
        passcode: secretCode
    ],
    values: [
        EmailAddress:emailData.to[0],
        message: content.message
    ]
]

// In order to get a json array, use a list containing the object
new JsonBuilder([jsonObj]).toPrettyString()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.