将JSON数据转换为ColdFusion结构

时间:2015-06-20 02:52:33

标签: arrays json web-services coldfusion

以下代码我的工作就像一个享受。它从我的SQL数据库表中获取数据并将其输出到cfc中的下面结构中,输出从我的移动应用程序调用,代码按需运行。

<cfset currentRow=1>    
<cfloop query="LT_Customers">

<cfset tempData = structNew()>
<cfset tempData["imei"] = LT_Customers.imei[currentRow]>
<cfset tempData["id"] = LT_Customers.id[currentRow]>
<cfset tempData["name"] = LT_Customers.last_name[currentRow]>
<cfset tempData["model"] = LT_Customers.Model[currentRow]>
<cfset tempData["trackee"] = LT_Customers.trackee[currentRow]>
<cfset tempData["mobile"] = LT_Customers.mobile[currentRow]>
<cfset tempData["app_user_mobile"] = LT_Customers.app_user_mobile[currentRow]>
<cfset arrayAppend(result, tempData)> 
<cfset currentRow=currentRow+1>
</cfloop>
<cfreturn result>
</cffunction>

我现在有来自Web服务的数据,该服务以JSON格式返回到我的页面。我想做的就是复制上面的内容,这样我的cfc函数就可以用与上面所示完全相同的方式输出JSON数据。 Web服务输出如下数据

<cfhttp url="http://api.sensis.com.au/v1/test/search?key=czsjp3f8xhd835vg6xfw8ber&query=vetinary%20and%20clinic&radius=1&location=-37.7833,144.9667" method="get" result="httpResp" timeout="120">
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
</cfhttp>

<cfset Data=DeserializeJSON(httpResp.filecontent)>

<cfdump var="#Data#">

花了很多时间研究如何实现上述目标,我需要承认,我需要那些自己更有经验的人的帮助。我只需要能够使用JSON内容生成与sql查询相同的结构(是的,我感谢列名称不同)

我提前感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:0)

您可以循环结果以构建您的结构。

<cfloop array="#data.results#" index="x">

 // build your results array in here...

 <cfset tempData = structNew()>
 <cfset tempData["imei"] = x.whatever>
 <cfset tempData["id"] = x.whatever>
 <cfset tempData["name"] = x.whatever>
 <cfset tempData["model"] = x.whatever>
 <cfset tempData["trackee"] = x.whatever>
 <cfset tempData["mobile"] = x.whatever>
 <cfset tempData["app_user_mobile"] = x.whatever>
 <cfset arrayAppend(result, Duplicate(tempData))> 

</cfloop>