How to convert an Object to JSON in Groovy?


How to convert an Object to JSON in Groovy without using any third party library?

2 Answers

7 years ago by

You can achieve this natively in Groovy, without using any third-party library using groovy.json.JsonOutput.toJson() Following is the sample code

​def colors = [ red : '#FF0000',
               black : '#000000',
               white : '#FFFFFF' ]
def jsonString = groovy.json.JsonOutput.toJson(colors);

println jsonString

Output:

{"red":"#FF0000","black":"#000000","white":"#FFFFFF"}

7 years ago by Karthik Divi

body(
[
[templateId : "c747053a-7d9b-4d4b-86f6-c540ab850ed5",
templateName : "SubstationAggregation",
category : "Aggregation",
state : "Released",
majorVersion : 2,
minorVersion : 0,
comment : "Created Template",
createdBy : "John",
createdOn : 1663573095085,
lastChanged : 1663573095085],
[templateId : "380a1013-a7d8-437a-9ec9-98179178e2e2",
templateName : "SubstationPRP",
category : "Substation",
state : "Draft",
majorVersion : 0,
minorVersion : 1,
comment : "Created Template",
createdBy : "John",
createdOn : 1663573095085,
lastChanged : 1663573095085]
]
)

2 years ago by SHRIYA BAJPAI