title: Support default serialisation for a custom class in a nested type
body: <p>I defined a class <code>A</code> and I am using objects of <code>A</code> inside other classes, containers and nested types.</p>
  
  <p>Example</p>
  
  <pre><code>a = A()
  b = [a,3,'hello'
  c = {'hey': b, 'huy': 3}
  d = [a,b,c]
  </code></pre>
  
  <p>I am interested in the json representation of <code>d</code>, so of course I have to specify how to behave when encountering an instance of <code>A</code>.</p>
  
  <p>For an object of class 'A' I want to get this (note that I am skipping att2, this shows that I don't what to use something like <code>a.__dict__</code>):</p>
  
  <pre><code>{
      class_name = 'A',
      att1 = '&lt;value of att1&gt;',
      att3 = '&lt;value of att3&gt;'
  }
  </code></pre>
  
  <p>att1 can be anything: an <code>A</code> instance, a default type, etc.</p>
  
  <p>I would like to be able to call <code>json.dumps(d)</code> and having the desired output, so what I trying to do is to tell the class <code>A</code> what to output when asked by the json serializer.</p>
  
  <p>I looked around and I have only found complex solutions in which a lambda or a class is passed to <code>json.dumps()</code> and I can't figure out why not just overriding a method called by the json serialiser, like when overriding <code>__str__()</code> or <code>__repr__()</code>.</p>
  
  <p>Maybe this is not possible?
  In such a case what could be a simple solution in my case? Note that in my real problem I have not only the class <code>A</code> but various custom classes nested together, so overriding the default serialiser would be the natural and easier solution.</p>
  
  <p><strong>One of my attempts</strong></p>
  
  <p>I am trying to follow the suggestion of line 160 of <a href="https://github.com/python/cpython/blob/master/Lib/json/encoder.py" rel="nofollow noreferrer">encoder.py</a></p>
  
  <p>So subclassed <code>A</code> from <code>json.JSONEncoder</code> and I declared the method</p>
  
  <pre><code>def default(self,obj):
      return 'valid custom json representation of A'
  </code></pre>
  
  <p>but this is not working and the exception of line 179 of the above link is raised. What is wrong with my code?</p>