In my project I needed to save domain info to files and these domains contained domains so I thought the easiest way would be XML and JSON.... having done some work in XML in Grails I decided to see how I fared in JSON.
Here's what happened:
import grails.converters.*
def report = MyDomain.get(1)
def json = ""
JSON.use("deep") {
def converter = report as JSON
converter.prettyPrint = true
json = converter.toString()
}
First off I grab a domain instance and then convert it to JSON using grails.converters.JSON. Note that grails.converters.deep is deprecated so to render your domain "deeply" you must use the configuration name "deep". I also grab the converter so I can alter some settings, specifically prettyPrint. This will render your domain in nicely formatted JSON!
So now I have a JSON string, how can I access its properties.... do I have to parse it by hand???? Fat chance...
def jsonArray = JSON.parse(json)
println jsonArray.myDomainProperty
So now we use JSON.parse() to convert our json String to an object that allows us to access our domain properties... sweet!
So there we have it, domain to json and back to an object that we could, if we wanted to, convert back to a domain...
Hope this saves people some time. Parsing and creating JSON???? Let Grails do the work...... again! :)
Hi, I saw your post at n4.nabble.com
ReplyDeleteand I am having exactly the same problem. Do you know if there is a workaround? Thanks a lot! mayra.ruano@backcountry.com
@Mayra update posted to
ReplyDeletehttp://n4.nabble.com/Poosible-Bug-in-JSON-Javassist-td1474496.html#a1554366
Thanks...curious...how did you find out about the JSON.use() method as I did not see it mentioned in docs (but I'm scatter-brained and may have skipped it somehow).
ReplyDelete