class OpenStruct
def self.json_create(object)
def self.json_create(object) new(object['t'] || object[:t]) end
def as_json(*)
# => #
OpenStruct.json_create(x)
\Method +JSON.create+ deserializes such a hash, returning a \OpenStruct object:
# => {"json_class"=>"OpenStruct", "t"=>{:name=>'Rowdy', :age=>nil}}
x = OpenStruct.new('name' => 'Rowdy', :age => nil).as_json
require 'json/add/ostruct'
returning a 2-element hash representing +self+:
\Method OpenStruct#as_json serializes +self+,
see Marshal[https://docs.ruby-lang.org/en/master/Marshal.html].
to serialize and deserialize a \OpenStruct object;
Methods OpenStruct#as_json and +OpenStruct.json_create+ may be used
def as_json(*) klass = self.class.name klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!" { JSON.create_id => klass, 't' => table, } end
def to_json(*args)
{"json_class":"OpenStruct","t":{'name':'Rowdy',"age":null}}
Output:
puts OpenStruct.new('name' => 'Rowdy', :age => nil).to_json
require 'json/add/ostruct'
Returns a JSON string representing +self+:
def to_json(*args) as_json.to_json(*args) end