Reputation: 3698
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?
Upvotes: 3
Views: 5339
Reputation: 50285
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()
Upvotes: 3