I am trying to process JSON data posted to a Rails (3.1.0) controller by accessing the data through the params hash. Unfortunately, Rails does not seem to process the data automatically (as the documentation and other questions on StackOverflow suggest).
The controller looks like:
class Api::EventsController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
unless params['event']['timestamp'].nil?
...
end
...
render :json => { :status => :success }
end
end
The HTTP request looks like this (captured using tcpdump):
POST /api/locations/1/events HTTP/1.1
Date: Mon, 10 Oct 2011 21:57:22 GMT+00:00
Content-Type: application/json; charset=UTF-8
Accept: application/json
Host: 10.0.2.2:3000
User-Agent: Restlet-Framework/2.1rc1
Authorization: Basic ...
Transfer-Encoding: chunked
Connection: Keep-Alive
4e
{"event":{"data_source":"ANDROID","timestamp":1318283841768,"type":"LEAVING"}}
0
In the above example, params['event'] is always nil. Using ActiveSupport::JSON.decode(request.body) to parse the JSON data works, but I would like to map the request body to parameters automatically.
Edit: request.params just contains routing information and request.request_parameters is completely empty.
What am I missing?
Are you sure that you’re sending a correct request? Reffering to RFC 2616, your last chunk should be empty to tell the receiver about the end of the transmission. Just adopt your request like that:
You might think of switching from Transfer-Encoding to Content-Length as well.
Transfer-Encoding is for streaming data. You may send several chunks of data without knowing their size in advance. You have to send an empty chunk to declare the transmission as completed.
Content-Length just specifies the Length of the data you will send, so that the receiver knows when the transmission reached the end.
Just in case you just forgot to paste that last chunk:
Overridden?
Did you override accidentally some of params, parameters, request_parameters, request? Why not try
request.paramsfor the same value orrequest.request_parametersfor the actual content hash {:event => …} without the additional dispatch stuff