问题
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