Skip to content

Instantly share code, notes, and snippets.

@tisba
Created October 23, 2010 12:35
Show Gist options
  • Select an option

  • Save tisba/642163 to your computer and use it in GitHub Desktop.

Select an option

Save tisba/642163 to your computer and use it in GitHub Desktop.
Nested object decoding with json-gem
require "rubygems"
# require "yajl/json_gem"
require "json"
class FooBarBase
attr_accessor :name, :type
def initialize(attributes = {})
attributes.each { |attr_name, attr_value| send("#{attr_name}=", attr_value) }
end
def to_hash
{:name => name, :type => type, :json_class => self.class.name}
end
def to_json(*args)
to_hash.to_json(*args)
end
def self.json_create(attributes = {})
attributes.delete("json_class")
new(attributes)
end
end
class Foo < FooBarBase; end
class Bar < FooBarBase; end
# create nested objects
bar = Bar.new("name" => "I'm bar!", "type" => "Bar")
foo = Foo.new("name" => "meh!", "type" => bar)
# encode them
json = foo.to_json
puts "JSON: #{json}"
# => JSON: {"type":{"type":"Bar","json_class":"Bar","name":"I'm
# bar!"},"json_class":"Foo","name":"meh!"}
# ... and get them back
foo = JSON.parse(json)
puts "Decoded object: #{foo.inspect}"
# => Decoded object: #<Foo:0x10104e7d0 @name="meh!", @type=#<Bar:0x10104f6f8
# @name="I'm bar!", @type="Bar">>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment