我有一个从Struct继承其行为的实体。它实例化如下:
Entity.new(id: 'asdf', name: 'bill', hair: 'brown')
当我将结构强制转换为json时,它就像这样:
#<struct Entity id=\"asdf\", name=\"bill\",
hair=\"brown\">"
编辑:^^忽略这个。我试图让事情变得模糊不清,但是我的irb会议是直接复制/粘贴:
"\"#<struct SorrisoEntity::EmailMessage recipient_email=nil, sender_email=\\\"poo@aol.com\\\", subject_line=nil, body=nil>\""
当我将它强制转换为JSON时,它不会抛出错误。但是当我尝试使用&#34; JSON.parse&#34;打电话,我收到这个错误:
JSON::ParserError: 757: unexpected token at '"#<struct Entity id=\"asdf\", name=\"bill\", hair=\"brown\">"
为什么Ruby不能适当地编组自定义结构?
答案 0 :(得分:3)
这没有记录,但是我必须阅读json
的ruby源代码及其测试才能得到这个,你需要手动require 'json/add/struct'
并传递参数:create_additions => true
来获取这工作,如下所示:
Entity = Struct.new('Entity', :id, :name, :hair)
entity = Entity.new("asdf", "bill", "brown")
# => #<struct Struct::Entity id={"id"=>"asdf", "name"=>"bill", "hair"=>"brown"}, name=nil, hair=nil>
require 'json/add/struct'
entity.to_json
# => "{\"json_class\":\"Struct::Entity\",\"v\":[\"asdf\",\"bill\",\"brown\"]}"
new_entity = JSON.parse(entity.to_json, :create_additions => true)
# => #<struct Struct::Entity id="asdf", name="bill", hair="brown">
new_entity.name
# => "bill"