title: Using custom to_json method in nested objects
body: <p>I have a data structure that uses the Set class from the Ruby Standard Library. I'd like to be able to serialize my data structure to a JSON string.</p>
  
  <p>By default, Set serializes as an Array:</p>
  
  <pre><code>&gt;&gt; s = Set.new [1,2,3]
  &gt;&gt; s.to_json
  =&gt; "[1,2,3]"
  </code></pre>
  
  <p>Which is fine until you try to deserialize it.</p>
  
  <p>So I defined a custom <code>to_json</code> method:</p>
  
  <pre><code>class Set
    def to_json(*a)
      {
        "json_class" =&gt; self.class.name,
        "data" =&gt; {
          "elements" =&gt; self.to_a
        }
      }.to_json(*a)
    end
  
    def self.json_create(o)
      new o["data"]["elements"]
    end
  end
  </code></pre>
  
  <p>Which works great:</p>
  
  <pre><code>&gt;&gt; s = Set.new [1,2,3]
  &gt;&gt; s.to_json
  =&gt; "{\"data\":{\"elements\":[1,2,3]},\"json_class\":\"Set\"}"
  </code></pre>
  
  <p>Until I put the Set into a Hash or something:</p>
  
  <pre><code>&gt;&gt; a = { 'set' =&gt; s }
  &gt;&gt; a.to_json
  =&gt; "{\"set\":[1,2,3]}"
  </code></pre>
  
  <p>Any idea why my custom <code>to_json</code> doesn't get called when the Set is nested inside another object?</p>