How do I get rails to parse params as JSON or XML instead of a string? I'm using rails 3.0.7.
Here's what I want to happen.
Parameters: {"user"=>{"email"=>"[email protected]", "password"=>"[FILTERED]"}}
Here's what happens
# controller
def create
logger.debug params
end
# curl from command line
curl -i -H 'Content-Type:application/xml' -H 'Accept:application/xml' -X POST -d "<user><email>[email protected]</email><password>password</password></user>" http://localhost:3000/api/v1/sessions.xml
# response
Started POST "/api/v1/sessions" for 127.0.0.1 at 2011-05-14 02:16:23 -0700
Processing by Api::V1::SessionsController#create as XML
Parameters: {"<user><email>[email protected]</email><password>password</password></user>"}
{"<user><email>[email protected]</email><password>password</password></user>", "action"=>"create", "controller"=>"api/v1/sessions", "format"=>"xml"}
Same thing happens with JSON.
An HTTP POST is typically name/value pairs.
Rails is doing its best try and figure out what you've passed it and turn it into a params hash, but it doesn't really make sense.
You can access the request directly:
def create
string = request.body.read
# if string is xml
object = Hash.from_xml(string)
# elsif string is JSON
object = ActiveSupport::JSON.decode(string)
end
Run rake middleware
, check that the ActionDispatch::ParamsParser
is used.
Take a look at actionpack-3.0.7/lib/action_dispatch/middleware/params_parser.rb
This is the middleware that's parsing the providing data to params hash. My guess is that the problem is with curl, as it doesn't post the request as you think it should. Maybe it needs a space after a colon (in headers), I don't know. I found this on google: http://snippets.dzone.com/posts/show/181.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With