如何使用Rails通过Web服务公开JSON格式的数据?
时间:2020-03-05 18:51:50 来源:igfitidea点击:
有没有一种简单的方法可以使用Rails将数据返回JSON中的Web服务客户端?
解决方案
回答
http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON
回答
Rails会修补我们最想拥有的#to_json`方法的大多数东西。
在我的头上,我们可以对散列,数组和ActiveRecord对象执行此操作,这些对象应该可以覆盖大约95%的用例。如果我们有自己的自定义对象,为它们编写自己的to_json
方法很简单,该方法可以将数据塞入哈希,然后返回经过json化的哈希。
回答
有一个插件可以做到这一点,
http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/
而且据我了解,该功能已经在Rails中。但是去看看那篇博客文章,那里有代码示例和解释。
回答
Rails资源为模型提供了RESTful接口。让我们来看看。
class Contact < ActiveRecord::Base ... end
map.resources :contacts
class ContactsController < ApplicationController ... def show @contact = Contact.find(params[:id] respond_to do |format| format.html format.xml {render :xml => @contact} format.js {render :json => @contact.json} end end ... end
因此,这为我们提供了API接口,而无需定义特殊方法即可获得所需的响应类型
例如。
/contacts/1 # Responds with regular html page /contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes /contacts/1.js # Responds with json output of Contact.find(1) and its attributes
回答
ActiveRecord还提供了与JSON交互的方法。要从AR对象中创建JSON,只需调用object.to_json。根据我的理解,要使用JSON创建AR对象,我们应该可以创建一个新的AR对象,然后调用object.from_json ..,但这对我不起作用。