Friday, June 15, 2012

Returning a complex object with specfic data types in a ColdFusion web service

Here is a folow-up on my previous post about returing an integer in a webservice. Most webservices return more then one value. In this example I will return a structure with a firstname and lastname:

<cfcomponent output="false">
   <cffunction name="giveMeAPerson" output="false" access="remote" returnType="person">
      <cfset var stReturn = createObject("component","person") />
      <cfset stReturn.firstName = "John" />
      <cfset stReturn.lastName = "Doe" />
      <cfset stReturn.age = "30" />
      <cfreturn stReturn />
   </cffunction>
</cfcomponent>

The returnType="person" points to person.cfc which is a value object with three properties: firstName, lastName and age with the according data type (string and numeric). (If the person.cfc is in a different folder than the web service cfc, then you must use the dot delimited path in the returnType field.)

If you want to use a specific data type for every struct key you will have to use XML. If you want the web service consumers to be able to fully use the different data types you have to specify the data types in the WSDL file. Save the generated WSDL to a file and point to this file in your component (see my previous post for the details on this). Next, edit the WSDL where the returnType is specified. Here I will change the data type "double" of the property "age" to "int". Next I will set the returntype of the function "giveMeAPerson" to "any".
Now it is time to construct the XML that has to be returned:

var XmlResponse = XmlNew();
XmlResponse.xmlRoot = XmlElemNew(XmlResponse,"urn:pointerToURN","giveMeAPersonResponse");
XmlResponse.xmlRoot.XmlAttributes['xsi:type'] = "giveMeAPersonResponse";
XmlResponse.xmlRoot.XmlChildren[1] = XmlElemNew(XmlResponse,"urn:customUrn","firstName");
XmlResponse.xmlRoot.XmlChildren[2] = XmlElemNew(XmlResponse,"lastName");
XmlResponse.xmlRoot.XmlChildren[3] = XmlElemNew(XmlResponse,"age");
XmlResponse.xmlRoot.firstName.XmlAttributes['xsi:type'] = "firstname";
XmlResponse.xmlRoot.lastname.XmlAttributes['xsi:type'] = "xsi:string";
XmlResponse.xmlRoot.age.XmlAttributes['xsi:type'] = "xsi:int";
XmlResponse.xmlRoot. firstName .XmlText = "John";
XmlResponse.xmlRoot.lastname.XmlText = "Doe"; 
XmlResponse.xmlRoot.age = JavaCast("int",30);

Then return the XmlResponse.

Note: In this example I used a custom data type for firstName. I did this to show you what to change to implement this. The custom data type must be defined in the WSDL under the given URN.
The conversion to int and string is not necessary, if you describe the type in the WSDL then ColdFusion will do the conversion.


No comments:

Post a Comment