coldfusion - receiving posted JSON data and parsing it

Steve picture Steve · Apr 25, 2011 · Viewed 10k times · Source

This is the first time I'm writing a cfc that will catch JSON data from an external web server that would be posting information.

I'm working with a new service that can be set to send us, via HTTP POST to a URL I specify, a JSON packet of information regarding failed transactions.

I figured I'd setup a CFC with remote access to capture and deserialize the JSON data into something we could then act on. However, I can't figure out how to setup the function in the CFC to received the data?

I set the URL to www.mydomain.com/com/processRemote.cfc?method=catchJSONdata&ReturnFormat=json

To test it, I setup a simple test page that should post session data:

<cfhttp 
  result="result"
  method="post" 
  url="http://www.mydomain.com/com/processRemote.cfc?method=catchJSONdata&ReturnFormat=json">

    <cfhttpparam type="header" name="content-type" value="application/json"/>
    <cfhttpparam type="body" value="#serializeJSON(session)#"/>

So where I'm lost is what's the cfargument name that I'd have in my cfc that I would initially store the JSON data in? I have no control over the remote service that would be sending the JSON data.

Thanks,

Answer

bpanulla picture bpanulla · Apr 25, 2011

If you're reading content from the HTTP request body you wont find it in arguments scope - you'll need to extract it directly from the request:

if (cgi.content_type EQ "application/json")
{
    myData = deserializeJSON(ToString(getHTTPRequestData().content));
}

I use the Taffy[1] framework for building services like this (Disclaimer: I actually helped write the part of the framework that handles this case).

[1] http://atuttle.github.com/Taffy/