March 31, 2011

How to return an Int from a ColdFusion Webservice

ColdFusion's Numeric type maps to a double in the automatically generated RPC WSDL. Consuming this in ColdFusion is not a big deal, but interfacing with more highly-typed environments, there are many times you want to return an int. How do you not return 2 + 2 as 4.0?

1. Write your own WSDL.
Save your CFC and capture the RPC generated WSDL by pointing your browser at http://mysite/mypath/myCFC.cfc?WSDL Grab the source, or clean up all the - added by your browser. Make sure there is no white space before the <?xml version tag.

Find the xsd:double in the Response message and change it to xsd:int.

2. Specify the WSDL in your component.
Add the wsdlfile="mywsdl.wsdl" attribute with the filename and add the attribute style="document" which is required for user-defined WSDLs.

3. Bind the webservice to the WSDL
ColdFusion does this automatically -- but it caches them. When a WSDL changes, you need to restart the service or go to "Data & Services -> Web Services" in CF Administration and refresh the service.

4. Change your cffunction to return "Any" instead of "Numeric"

5. In your cfreturn, instantiate a Java Integer
<cfreturn createObject("java","java.lang.Integer").init(JavaCast("int",myvalue)) />

There it is! You've just gotten rid of ".0" in only five steps. This also works, mutatis mutandis, for accepting ints as input parameters (see sample).
Sample cfc Sample wsdl

What is this?
Political hacks: my life is enriched by finding small things like this on the Internet to save time figuring out what somebody has already done. I'm just trying to give back...

Tech hacks: this is a mostly political blog. Poke around if you are so inclined and not easily offended.

Posted by John Kranz at March 31, 2011 10:55 AM

Thanks so much for your awesome help! I spent (litterally) the last 14 hours on this.

Posted by: Evik James at August 14, 2011 6:55 PM

Glad you found it! I remember a bit of grinding on this...


Posted by: jk at August 15, 2011 10:30 AM | What do you think? [2]