是否有一种使用Rails以JSON方式将数据返回给Web服务客户端的简单方法?
答案 0 :(得分:10)
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
答案 1 :(得分:4)
答案 2 :(得分:2)
Rails monkeypatches你关心的大多数东西都有#to_json
方法。
在我的脑海中,您可以为哈希,数组和ActiveRecord对象执行此操作,这些对象应该涵盖您可能需要的大约95%的用例。如果你有自己的自定义对象,那么为它们编写自己的to_json
方法是微不足道的,它可以将数据堵塞到哈希中,然后返回jsonized哈希。
答案 3 :(得分:1)
有一个插件可以做到这一点, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/
根据我的理解,这个功能已经在Rails中了。但是看看那篇博文,有代码示例和解释。
答案 4 :(得分:0)
ActiveRecord还提供了与JSON交互的方法。要从AR对象创建JSON,只需调用object.to_json即可。要使用JSON创建AR对象,您应该能够创建一个新的AR对象,然后根据我的理解调用object.from_json ..但这对我不起作用。