简体   繁体   English

Ruby to_json对象输出实例变量

[英]Ruby to_json on object to output instance variables

I'm using Sinatra and trying to output an object in JSON by using the 'json' gem and calling the .to_json method. 我正在使用Sinatra并尝试通过使用'json'gem并调用.to_json方法在JSON中输出对象。 I expected the output to be JSON with the symbols in the attr_reader section and their values. 我期望输出为JSON,其中包含attr_reader部分中的符号及其值。

Here's my code. 这是我的代码。 Do I need to do anything special to get this to work? 我需要做一些特别的事情才能使它起作用吗?

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

All I get from the output is the objects default to_s. 我从输出中得到的只是对象默认为to_s。

"#<Foo:0x007fe372a3ba80>"

You need to specify a to_json method on your class. 您需要在类上指定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

Looks like you need a to_hash method 看起来您需要一个to_hash方法

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

Otherwise Foo is not a type recognizable by json. 否则Foo不能被json识别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM