默認編碼爲JSON使用JSON紅寶石寶石當結構實例將顯示爲一個字符串:
require 'json'
array = [#<struct id=1, car='red'>, #<struct id=2, car='yellow'>, #<struct id=3, car='green'>] # assuming real structure code in the array
puts array.to_json
打印
["#<struct id=1, car='red'>", "#<struct id=2, car='yellow'>", "#<struct id=3, car='green'>"]
這顯然不是你想要什麼。
接下來的邏輯步驟是確保您的結構實例可以正確地序列化爲JSON,以及從JSON創建回來。
要做到這一點,你可以改變你的結構聲明:
YourStruct = Struct.new(:id, :car)
class YourStruct
def to_json(*a)
{:id => self.id, :car => self.car}.to_json(*a)
end
def self.json_create(o)
new(o['id'], o['car'])
end
end
所以,你現在可以寫:
a = [ YourStruct.new(1, 'toy'), YourStruct.new(2, 'test')]
puts a.to_json
它打印
[{"id": 1,"car":"toy"},{"id": 2,"car":"test"}]
,並反序列化來自JSON:
YourStruct.json_create(JSON.parse('{"id": 1,"car":"toy"}'))
# => #<struct YourStruct id=1, car="toy">
所需的輸出無效json。你的意思是一個數組? [...] – tokland