首页 > 解决方案 > 返回一个 JSON 对象

问题描述

有没有办法通过 ColdFusion 中的函数返回一个真正的 JSON 对象?我当前的解决方案是将查询转换为字符串,并在另一个 CF 文件中将其转换回 JSON 对象:

<cffunction name="addLicense" access="remote" returntype="string" returnFormat="JSON" httpmethod="POST">
  <cfquery datasource="hostmanager" name="createCustomer">
    SELECT * FROM license
  </cfquery>
  <cfreturn serializeJSON(createCustomer)>
</cffunction>

标签: jsonrestcoldfusioncfml

解决方案


有许多不同的方法可以使用 serializeJSON

<cfscript>
    myQuery = queryNew("id,name,amount","Integer,Varchar,Integer", 
                [ 
                        {id=1,name="One",amount=15}, 
                        {id=2,name="Two",amount=18}, 
                        {id=3,name="Three",amount=32} 
                ]); 
    writeOutput("The new query is:")
    writeDump(myQuery)
</cfscript>

<cfoutput>
    <h4>Default</h4>
    <p><code>#serializeJSON(myQuery)#</code></p>
    <h4>Row</h4>
    <p><code>#serializeJSON(myQuery, "row")#</code></p>
     <h4>Column</h4>
    <p><code>#serializeJSON(myQuery, "column")#</code></p>
     <h4>Struct</h4>
    <p><code>#serializeJSON(myQuery, "struct")#</code></p>
</cfoutput>

结果是

在此处输入图像描述

参见:https ://cffiddle.org/app/file?filepath=58f7cee2-dabb-42f8-91ef-7dd41e1691c0/49ad94cb-23e4-4c9c-9986-b7c1d4c15e3a/c818a99e-4476-4625-8bec-657bcfa9b0e2.cfm


推荐阅读