1unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED 2 require 'json' 3end 4 5# Struct serialization/deserialization 6class Struct 7 8 # Deserializes JSON string by constructing new Struct object with values 9 # <tt>v</tt> serialized by <tt>to_json</tt>. 10 def self.json_create(object) 11 new(*object['v']) 12 end 13 14 # Returns a hash, that will be turned into a JSON object and represent this 15 # object. 16 def as_json(*) 17 klass = self.class.name 18 klass.to_s.empty? and raise JSON::JSONError, "Only named structs are supported!" 19 { 20 JSON.create_id => klass, 21 'v' => values, 22 } 23 end 24 25 # Stores class name (Struct) with Struct values <tt>v</tt> as a JSON string. 26 # Only named structs are supported. 27 def to_json(*args) 28 as_json.to_json(*args) 29 end 30end 31