ColdFusion 10 REST API: How to parse JSON in body of payload

风格不统一 提交于 2020-02-28 06:56:23

问题


I'm using ColdFusion 10's new build-in RESTful web services feature. When posting data, I'd like to send the payload as JSON in the body of the request. For example:

PUT https://mycompany.com/rest/v1.0/widget/261469 HTTP/1.1
Host: mycompany.com
Connection: keep-alive
Content-Length: 13
Content-Type: application/json

{"foo":"bar"}

Once this data is posted through the API, how should I parse and deserialize the JSON data on the server? Does ColdFusion REST service have a built-in way to do this? It seems that there is native support to deserialize "form" type (i.e. content-type application/x-www-form-urlencoded) by setting the restargsource attribute on cfargument to "form", but I'm not able to find any examples on how to deserialize JSON data natively. I was hoping for something like restargsource="json", but that doesn't exist. What is the recommended way to do this?


回答1:


After a lot of research, it doesn't look like there's a native way for ColdFusion 10's REST API request handler to parse JSON requests automatically for us. We need to do this manually as follows:

<cfset var json = ToString(GetHttpRequestData().content) />
<cfif !IsJSON(json)>
    <cfthrow errorCode="400" type="ArgumentException" message="#"Invalid JSON string: " & json#" />
</cfif>

<cfset var jsonObject = DeserializeJSON(json) />



回答2:


You can also try

VARIABLES.postJSON = StructNew();
StructInsert(VARIABLES.postJSON, 'parameter1','xxx');

then user #SerializeJSON(VARIABLES.postJSON)#



来源:https://stackoverflow.com/questions/15708804/coldfusion-10-rest-api-how-to-parse-json-in-body-of-payload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!