【问题标题】:Ruby to_json on object to output instance variablesRuby to_json on object 输出实例变量
【发布时间】:2012-10-03 11:58:49
【问题描述】:

我正在使用 Sinatra 并尝试通过使用 'json' gem 并调用 .to_json 方法以 JSON 格式输出对象。我希望输出是 JSON,其中包含 attr_reader 部分中的符号及其值。

这是我的代码。我需要做一些特别的事情才能让它工作吗?

require "sinatra"
require "json"    

class Foo
  attr_reader :id, :name

  def initialize(id, name)
    @id = id
    @name = name
  end
end

get '/start' do
  content_type :json
  Foo.new(2, "john").to_json
end

我从输出中得到的只是默认 to_s 的对象。

"#<Foo:0x007fe372a3ba80>"

【问题讨论】:

标签: ruby json sinatra


【解决方案1】:

你需要在你的类上指定一个 to_json 方法。

class Foo
  attr_reader :id, :name

  def initialize(id, name)
    @id = id
    @name = name
  end

  def to_json 
    {:id => @id, :name => @name}.to_json
  end
end

【讨论】:

    【解决方案2】:

    看起来你需要一个to_hash 方法

    class Foo
      def to_hash
        {:id => @id, :name => @name}
      end
    end
    

    否则 Foo 不是 json 可识别的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 2019-05-09
      • 2013-07-08
      • 2010-10-31
      相关资源
      最近更新 更多