0

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.new
  @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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have tried this before, it results in IOError exception in class A, saying to_json "not opened for reading"...
1

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.