From: Brian Candler Date: 2011-02-10T04:07:17+09:00 Subject: Re: Best practice to create a JSON string of one object containing an array of other objects using R > But it results in IOError exception in class A, saying to_json "not > opened for reading"... > > I am sure we can do better? I think it would be much better to make the class an attribute of the JSON object, not build a new JSON object of {class => {attributes}} If you look at the tests/ directory of the json or json_pure gem, you'll see that they use 'json_class' for this purpose. e.g. class A def initialize(a) @a = a end attr_reader :a def ==(other) a == other.a end def self.json_create(object) new(*object['args']) end def to_json(*args) { 'json_class' => self.class.name, 'args' => [ @a ], }.to_json(*args) end end The use of the 'args' element (being the array of arguments to #new) is fairly ugly. I would rather expose the instance variables as members of the JSON object: class A def initialize(a) @a = a end attr_reader :a def self.json_create(object) new(object['a']) end def to_json(*args) { 'json_class' => self.class.name, 'a' => @a, }.to_json(*args) end end a1 = A.new([123, 456]) puts a1.inspect str = a1.to_json puts str a2 = JSON.parse(str) puts a2.inspect HTH, Brian. -- Posted via http://www.ruby-forum.com/.