Sto provando a serializzare una semplice struct su JSON che funziona bene, ma non riesco a farlo per creare un'istanza di quella struct dal JSON. Ecco come sto cercando di farlo.Ruby serialize struct con JSON
require 'rubygems'
require 'json'
Person = Struct.new(:name, :age)
json = Person.new('Adam', 19).to_json
puts json
me = JSON.load(json)
puts me.name
e ottengo il seguente output:
"#<struct Person name=\"Adam\", age=19>"
/usr/lib/ruby/1.9.1/json/common.rb:148:in `parse': 746: unexpected token at '"#<struct Person name=\"Adam\", age=19>"' (JSON::ParserError)
from /usr/lib/ruby/1.9.1/json/common.rb:148:in `parse'
from /usr/lib/ruby/1.9.1/json/common.rb:309:in `load'
from why.rb:9:in `<main>'
Grazie che ha funzionato perfettamente. Vorrei solo far notare a chiunque leggendo questo in futuro che il metodo to_h è stato aggiunto in ruby 2.0, quindi se stai usando 1.9.3 come lo dovevo aggiornare. –