class OpenStruct
Public Class Methods
Source
# File ext/json/lib/json/add/ostruct.rb, line 13 def self.json_create(object) new(object['t'] || object[:t]) end
参见 as_json。
Public Instance Methods
Source
# File ext/json/lib/json/add/ostruct.rb, line 33 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
方法 OpenStruct#as_json 和 OpenStruct.json_create 可用于序列化和反序列化 OpenStruct 对象;参见 Marshal。
方法 OpenStruct#as_json 序列化 self,返回一个代表 self 的两元素哈希
require 'json/add/ostruct' x = OpenStruct.new('name' => 'Rowdy', :age => nil).as_json # => {"json_class"=>"OpenStruct", "t"=>{:name=>'Rowdy', :age=>nil}}
方法 JSON.create 反序列化这样的哈希,返回一个 OpenStruct 对象
OpenStruct.json_create(x) # => #<OpenStruct name='Rowdy', age=nil>
Source
# File ext/json/lib/json/add/ostruct.rb, line 51 def to_json(*args) as_json.to_json(*args) end
返回一个代表 self 的 JSON 字符串
require 'json/add/ostruct' puts OpenStruct.new('name' => 'Rowdy', :age => nil).to_json
输出
{"json_class":"OpenStruct","t":{'name':'Rowdy',"age":null}}