Returning ColdFusion 9 ORM objects with JSON
Last week I was working on a client’s project that makes heavy use of ColdFusion 9′s ORM features. Everything we’d done with ORM up to that point had been going really well and I continue to be impressed by the amount of time ORM saves me in development. I had gotten to a point in the project where I needed to be able to use AJAX calls from jQuery to manage some of the data in the database. Based on my experiences using a RemoteFacade.cfc to feed data to a Flex app, I thought it should be pretty easy. Several hours later, I realized that my particular use case for this was anything but easy.
As near as I can tell, the culprit is the serializeJSON() method that ColdFusion uses to convert complex objects into JSON notation. It doesn’t seem to work correctly on ORM objects. To test my theory, I manually built a structure and inserted each simple property from the ORM object. I then created a key in the structure that was an array and manually populated several items in the array each with a structure of data. When I returned that from the CFC as JSON, the array and all the structures it contained came across the wire just fine.
I’m not sure if this is a bug in the serializeJSON() method or if serializeJSON() wasn’t meant to handle objects. Whatever the case, this issue leads to quite a bit of extra work if you need to return an object via JSON and include its properties that are composed of other objects. I’d definitely be interested in hearing from anyone who has successfully done this with ORM and AJAX to see if I’ve done something incorrectly in my code.