Rails 3 and application/json

I have a rails 2 app that I am upgrading to rails 3.

I am exposing a web service to a phone app. When I make a request from the phone application the CONTENT_TYPE is application/json

In rails 2 my controller recognizes this as json, but in rails 3 my controller recognizes it as html.

      respond_to do |format|         format.html { }         format.json { }       end

Any ideas why the format isn't being set to json in rails 3? Do i have to do something to enable json routing?

This might be useful: http://ryandaigle.com/articles/2009/8/10/what-s-new-in-edge-rails-default-restful-rendering

Best regards

Peter De Berdt

I replied to this earlier but I think I may have accidentally clicked discard instead of send. Sorry if this is a duplicate:

I tried that method (using respond_with). Even then the requests gets processed as HTML.

So on my Rails 2 setup just setting CONTENT_TYPE = 'application/json' causes the request to be processed as a json format.

On Rails 3 that isn't working so everything gets set as HTML. Do I need to set HTTP_ACCEPT instead of CONTENT_TYPE? I get the feeling Rails 3 uses CONTENT_TYPE for the incoming parsing (since the incoming json is parsed correctly) and I need to set some other type to force a JSON *response*. It isn't clear where that should be set though.

Thanks

Joe

Can you verify that the following headers are present, the accept header might actually be what you’re missing out on:

Accept: application/json

Content-Type: application/json

If everything goes well, you should get back a response with this in the header:

Content-Type: application/json; charset=utf-8

For XML that would be:

Accept: application/xml

Content-Type: application/xml

Best regards

Peter De Berdt

I will try to set HTTP_ACCEPT when I get home. I know it’s not being set now, but I wasn’t sure if it was required or not.

Something must have changed from 2.3.4 to 3 or I set some configuration in 2.3.4 that I dont remember…

Well, the Accept header is what tells the server what response you accept, while the Content-Type header tells the server what type of data the posted data is, as you can read at http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

Rails 2 might have been more forgiving or you might have just appended .json to the url, but Rails 3 has the correct behaviour.

Best regards

Peter De Berdt

Thanks. Just in case anyone is curious adding the Accept headers worked perfect!