AbuMariam AbuMariam - 4 months ago 26
JSON Question

How to create a JSON array as string from groovy objects?

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": "john@doe.com",
"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?

Answer

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()