Friday, March 27, 2015

Returning a structure containing an array of Structures from ColdFusion Webservice

Encountered this issue when I was trying to return a structure containing an Array of structures. The structure I returned contained the array but with empty structures. Though it was accessed from another Coldfusion system, the web service interprets the complex data structure in a different way.

There are couple of useful documents at the adobe help docs on how to handle the complex data types in case of web services.

This is how the code looked when I encountered the issue.


  1. <cfcomponent>

  2.     <cffunction name="testStructReturn" access="remote" returntype="struct">
  3.          
  4.           <cfset var resultStruct = StructNew() />
  5.           <cfset resultStruct.testArray = ArrayNew(1) />
  6.           <cfset var tempStruct = StructNew() />

  7.           <cfset var qryResult = QueryNew("") />

  8.           <cfquery name="qryResult" datasource="testDSN">
  9.                Select first_name, 
  10.                           last_name 
  11.                from employee
  12.           </cfquery>

  13.          <cfset resultStruct.companyName = "zzz company" />
  14.          <cfset resultStruct.companyLocation = "Gandhi Bazaar, Tirunelveli - 2" />
  15.          
  16.          <cfloop from="1" to="#qryResult.RecordCount#" index="i">

  17.                <cfset tempStruct = StructNew() />
  18.                <cfset tempStruct.firstName = qryResult[i][0] />
  19.                <cfset tempStruct.lastName = qryResult[i][1] />
  20.                 
  21.                 <cfset ArrayAppend(resultStruct.testArray, tempStruct) />
  22.           
  23.           </cfloop>

  24.           <cfreturn resultStruct />
  25.     </cffunction>
  26. </cfcomponent>



The above code returned the resultStruct with the array, but empty structures within it. To resolve this. I had to change this line of code 26 to read like this..

<cfset ArrayAppend(resultStruct.testArray, serializeJSON(tempStruct)) />.

Happy coding!