简体   繁体   中英

How to parse a custom Ruby struct from JSON

I've got an entity that inherits its behavior from Struct. It instantiates like this:

Entity.new(id: 'asdf', name: 'bill', hair: 'brown')

When I coerce the struct to json, it loks like this:

#<struct Entity id=\\"asdf\\", name=\\"bill\\", hair=\\"brown\\">"

EDIT: ^^ ignore this. I was trying to keep things vague, but here's a straight copy/paste from my irb session:

"\\"#<struct SorrisoEntity::EmailMessage recipient_email=nil, sender_email=\\\\\\"poo@aol.com\\\\\\", subject_line=nil, body=nil>\\""

When I coerce it to JSON, it doesn't throw an error. But when I try to a "JSON.parse" call, I get this error:

JSON::ParserError: 757: unexpected token at '"#<struct Entity id=\\"asdf\\", name=\\"bill\\", hair=\\"brown\\">"

Why Ruby won't marshall the custom struct appropriately?

This is not documented, but I had to read the ruby source code for json and its test to get this, you need to manually require 'json/add/struct' and pass the arguments :create_additions => true to get this working, as shown below:

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" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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