Search code examples
mysqlweb-servicescoldfusionrailolucee

Coldfusion Lucee 4.5.2.018 (Linux) - REST service (can't cast String) JSON


working on REST web-service, i don't have much experience coldfusion web-services.It is very basic web-service.Please if you guys can point me, what im doing wrong. it will be great help.

Application Server : Lucee 4.5.2.018 (Linux)

Please find below my code.

Component-Function/ Web-Service.

<cfcomponent rest="true" restpath="/hello">

    <cffunction name="formPost" access="remote" returnType="struct" httpMethod="POST" restPath="/name" hint="POST Method" produces="application/json">
           <cfargument name="firstname" type="String" restArgSource="Form">
           <cfargument name="lastname" type="String" restArgSource="Form">
         <cfset myStruct =  structnew()>  
           <cfset myStruct.FirstName = firstname>
           <cfset myStruct.LastName  = lastname>

            <cfquery name="Qry" datasource="myDSN">
                select col1,col2 from myTableData
            </cfquery>
           <cfset myJsonVar = serializeJSON(Qry) />
           <cfreturn myJsonVar>
    </cffunction>
</cfcomponent>

Calling web-service

<cfhttp url="http://mydev:8888/rest/Example/hello/name" method="POST"  result="res"  port="8888" >
        <cfhttpparam type="header" name="Accept" value="application/json">
        <cfhttpparam type="formfield" name="firstname" value="Dan">
        <cfhttpparam type="formfield" name="lastname" value="Gates">
</cfhttp>
<cfdump var="#res#">

Problem: When defining returnType="struct" Error string can't cast String [{"COLUMNS":["COL1","COL2"],"DATA":[["0","7777777"],["0","888888"]]}] to a value of type [struct]

When defining returnType="string" No error coming "{\"COLUMNS\":[\"COL1\",\"COL2\"],\"DATA\":[[\"0\",\"7777777\"],[\"0\",\"888888\"]]}"

Trying get [DATA] values in loop

<cfloop from="1" to="#ArrayLen(d.DATA)#" index="i"> <cfloop from="1" to=#ArrayLen(d.DATA[i])# index="j"> <cfset resultSrt =d.COLUMNS[j]&" = " &d.DATA[i][j]> #resultSrt#<br> </cfloop> </cfloop>

Message: No matching property [DATA] found in [string] Stacktrace:The Error Occurred in /opt/lucee/tomcat/webapps/ROOT/calling.cfm: line 52 50: 51: 52: <cfloop from="1" to="#ArrayLen(d.DATA)#" index="i"> 53: <cfloop from="1" to=#ArrayLen(d.DATA[i])# index="j"> 54: <cfset resultSrt =d.COLUMNS[j]&" = " &d.DATA[i][j]> Output


Solution

  • First of all since you are returning a query, you should set returnType to Query.

    If you have set produces attribute of cffunction to application/json, in that case you don't need to perform explicit JSON serialization while returning data. ColdFusion will automatically do it for you. You can just write:

    <cfreturn Qry />
    

    To read the result returned from the service you need to deserialize the data. Like this:

    <cfdump var="#deserializeJson(res.filecontent)#">