6

有没有一种简单的方法可以使用 Rails 以 JSON 格式将数据返回给 Web 服务客户端?

4

5 回答 5

11

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
于 2008-10-29T01:26:16.420 回答
4

http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON

于 2008-09-11T21:28:19.233 回答
2

Rails monkeypatches 大多数你关心的东西都有一个#to_json方法。

在我的脑海中,您可以对哈希、数组和 ActiveRecord 对象执行此操作,它们应该涵盖您可能想要的大约 95% 的用例。如果您有自己的自定义对象,则为它们编写自己的to_json方法很简单,它可以将数据塞入散列,然后返回 jsonized 散列。

于 2008-09-11T22:00:14.600 回答
1

有一个插件可以做到这一点, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/

据我了解,这个功能已经在 Rails 中了。但是去看看那个博客文章,有代码示例和解释。

于 2008-09-16T09:18:29.430 回答
0

ActiveRecord 还提供了与 JSON 交互的方法。要从 AR 对象创建 JSON,只需调用 object.to_json。要从 JSON 创建一个 AR 对象,您应该能够创建一个新的 AR 对象,然后调用 object.from_json .. 据我所知,但这对我不起作用。

于 2008-12-09T17:11:38.513 回答