Tuesday, February 7, 2017

Grails JSON Parser

Grails JSON Parser


Here is a quick example on parsing JSON in grails using groovy (surprisingly, google isnt returning any good hits). Also, if you needed this ability in just straight groovy, I am sure you could include the specific grails jar in your classpath.
import grails.converters.*

def jsonArray = JSON.parse("""[foo,bar, { a: JSONObject }]""")
println "Class of jsonArray: ${jsonArray.class.name}"
jsonArray.each { println "Value: ${it}" }

FYI, it appears from the mailing list this was added around 1.0 RC1.

Building JSON is super easy too in grails/groovy using the render as. And dont forget to import grails.converters.
render Book.list(params) as JSON

Update: Read my recent article on testing REST Services that return JSON using groovy and httpbuilder.

Available link for download