Serialize and Deserialize of OnappMarket classes
De-serialize from a hash of values and create an instance
hash - Hash of values
Object
# File lib/onapp_market/api/serialize.rb, line 265 def from_hash(hash) return nil unless hash[:type] || hash['type'] # Instantiate class klass = Classes.get(hash[:type]) if hash[:type] klass = Classes.get(hash['type']) if hash['type'] return nil if klass == nil klass.new hash end
De-serialize and create an instance of a class
json Raw json
Object
# File lib/onapp_market/api/serialize.rb, line 279 def from_json(json) # Parse the JSON hash = JSON.parse(json, {:symbolize_names => true}) OnappMarket::API::Serialize.from_hash(hash) end
Serialize a class to a hash and include it's type for de-serializing later
item - Item to serialize
Hash
# File lib/onapp_market/api/serialize.rb, line 241 def to_hash(item, role = :none) # Check there is a type raise "Attempting to serialize class with no type" unless item.instance_variable_defined? "@type" hash = Hash[item.get_accessors(role).map do |accessor| value = item.instance_variable_get("@#{accessor.to_s}") value = value.to_s unless value.is_a?(String) or value.is_a?(Fixnum) or value.is_a?(Float) or value.is_a?(Hash) or value.is_a?(Array) or value.is_a?(TrueClass) or value.is_a?(FalseClass) [accessor, value] end ] end
Serialize a class to JSON and include it's type for de-serializing later
item - Item to serialize
JSON
# File lib/onapp_market/api/serialize.rb, line 255 def to_json(item, role = :none) # Generate a JSON from the instance variables JSON.generate(OnappMarket::API::Serialize.to_hash(item, role)) end