Ruby on rails 如何在Rails3中将哈希呈现为JSON

Ruby on rails 如何在Rails3中将哈希呈现为JSON,ruby-on-rails,json,api,ruby-on-rails-3,Ruby On Rails,Json,Api,Ruby On Rails 3,我在Rails 3中找到了如何渲染ActiveRecord对象,但是我无法理解如何渲染任何自定义对象。我正在编写一个没有ActiveRecord的应用程序。我试过这样做: class AppController < ApplicationController respond_to :json ... def start app.start format.json { render :json => {'ok'=>true} } end end

我在Rails 3中找到了如何渲染ActiveRecord对象,但是我无法理解如何渲染任何自定义对象。我正在编写一个没有ActiveRecord的应用程序。我试过这样做:

class AppController < ApplicationController
  respond_to :json

  ...
  def start
    app.start
    format.json { render :json => {'ok'=>true} }
  end
end
class AppController{'ok'=>true}
结束
结束

当您指定一个
响应
时,那么在您的操作中,您将使用进行匹配的
响应:

class AppControlls < ApplicationController
  respond_to :json

  def index
    hash = { :ok => true }
    respond_with(hash)
  end
end
class AppControllstrue}
用(散列)响应_
结束
结束

看起来您正在将旧的
respond_to do | format |
样式块与新的
respond_to
respond_与
语法混为一谈。解释得很好。

这非常接近。但是,它不会自动将哈希转换为json。这就是最终的结果:

class AppControlls < ApplicationController
  respond_to :json

  def start
    app.start
    respond_with( { :ok => true }.to_json )
  end
end
class AppControllstrue}.to_json)响应_
结束
结束

谢谢您的帮助。

format.json{render json:{ok:true}}
应该可以工作

对于获得命名错误的用户,请尝试以下操作:

class AppController < ApplicationController
  respond_to :json

  ...
  def start
    app.start
    render json: { :ok => true }
  end
end
class AppControllertrue}
结束
结束
class AppControllertrue}
用(hash.as_json)响应
结束
结束

您永远不应该使用to_json来创建表示,而只是使用表示。

{:ok=>true}。json给出了NoMethodError:undefined方法` json'for{:ok=>true}:Hashto_json没有给出错误,但我相信它不是必需的。(自动转换对我来说很好)。注意。要使自动转换生效:格式必须为json。
class AppController < ApplicationController

respond_to :json

def index
  hash = { :ok => true }
  respond_with(hash.as_json)
end

end