Best practice to create a JSON string of one object containing an array of other objects using Ruby?
What is a good practice to create a JSON string of one object (object of class A) containing an array of objects (objects of class B)? I am particularly interessted in the implementation of class's A to_json method.
Assuming class A looks as follows:
class A
attr_accessor :items
def initialize()
@items = Array.new
end
def to_json(*a)
?SECRET OF THE DAY?
end
end
and class B:
class B
def to_json(*a)
{"class B" => "class B"}.to_json(*a)
end
end
The best solution I got so far is:
def to_json(*a)
json = Array.ne开发者_如何学JAVAw
@items.each do |item|
json << item.to_json(*a)
end
{"class A" => json}.to_json(*a)
end
Assuming there is only one item in array of an object of class A, the resulting JSON string looks as follows:
{"class A":["{\"class B\":\"class B\"}"]}
I am sure we can do better?
I would do this instead
def to_json(*a)
{"class A" => @items}.to_json(*a)
end
The problem with your approach is that your @items
array contains strings, not objects. In that case your to_json will create an array of strings, not an array of objects.
Reinstalling/upgrading json/json_pure to 1.5.1 finally solved the IOError exception issue.
Using: Rails 3.0.3 ruby 1.9.2p136 (2010-12-25 revision 30365) [i386-darwin9.8.0] json 1.5.1 json_pure 1.5.1
Refer to http://www.ruby-forum.com/topic/1052511#new for further guidance...
精彩评论