我有一个Ruby数据结构:
class Albums
attr_accessor :title, :url
def initialize(title, url)
@title = title
@url = url
end
end
class Albumlist < Albums
attr_accessor :id, :albums
def initialize(id)
@id = id
@albums = Array.new
end
end
我制作了一个 Albumlist 的数组,看起来像(使用.inspect方法):
[#<Albumlist:0x8db6390 @id="abc",@albums=[
#<Albums:0x8db6098 @title="123", @url="test">,
#<Albums:0x8db5fe4 @title="456", @url="test">
]>,
#<Albumlist:0x8f4042c @id="def", @albums=[
#<Albums:0x8f49f2c @title="Untitled Album", @url="test">
]>
]
我不确定这个数组是否正常但是一旦我在这个数组上使用方法.to_json或JSON.generate(),我得到的只是:
["#<Albumlist:0x8db6390>","#<Albumlist:0x8f4042c>"]
看起来Ruby返回对象实例的“引用”。 我想用JSON转换这个数组,看起来像
[
{
"id":"abc"
"albums":[
{
"title":"123",
"url":"test"
},
{
"title":"456",
"url":"test"
}
]
},
{
"id":"def"
"albums":[
{
"title":"Untitled Album",
"url":"test"
}
]
}
]
我相信我遗漏了一些东西,例如将数组转换为某种中间对象?
编辑:替代解决方案
在类Albumlist中定义一个to_json方法:
def to_json(*a)
{
"id" => @id,
"albums" => @albums
}.to_json(*a)
end
然后使用它..
答案 0 :(得分:1)
这里有效,可能你没有在正确的时刻应用这个方法,让我们试试吧,首先,用这样的东西专注于数组:
require 'rubygems'
require 'active_support/all'
class Albums
attr_accessor :title, :url
def initialize(title, url)
@title = title
@url = url
end
end
class Albumlist < Albums
attr_accessor :id, :albums
def initialize(id)
@id = id
@albums = Array.new
end
end
a = Albums.new("a", "www.a.com")
b = Albums.new("b", "www.b.com")
c = Albums.new("c", "www.c.com")
list_of_albums_list = Array.new
list_a = Albumlist.new(1)
list_b = Albumlist.new(2)
list_a.albums << a
list_a.albums << b
list_b.albums << c
list_of_albums_list << list_a
list_of_albums_list << list_b
puts list_of_albums_list.to_json
输出是:
[{"albums":[{"title":"a","url":"www.a.com"},{"title":"b","url":"www.b.com"}],"id":1},{"albums":[{"title":"c","url":"www.c.com"}],"id":2}]
因此该方法按预期工作。