I ended up doing the following.
class ShadingInfoEncoder(json.JSONEncoder):
def _iterencode(self, o, markers=None):
jsonPlaceholderNames = (("_ShaderInfo", ShaderInfo),
("_ShapeInfo", ShapeInfo),
("_NodeInfo", NodeInfo))
for jsonPlaceholderName, cls in customIterEncode:
if isinstance(o, cls):
yield '{"' + jsonPlaceholderName+ '": '
for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
yield chunk
yield '}'
break
else:
for chunk in super(ShadingInfoEncoder, self)._iterencode(o, markers):
yield chunk
I assume this is not the best way to do this, yet I'm sharing it here to see if anyone else can tell me what I'm doing wrong and show me the best way to do this!
Note that I'm using nested tuples instead of a dictionary because I wanted to keep the order they were listed so I could - in this example - override ShaderInfo becoming _NodeInfo if ShaderInfo was an object that inherited from NodeInfo.
My decoder is set up to do something along the lines of (simplified and part of code):
class ShadingInfoDecoder(json.JSONDecoder):
def decode(self, obj):
obj = super(ShadingInfoDecoder,self).decode(s)
if isinstance(obj, dict):
decoders = [("_set",self.setDecode),
("_NodeInfo", self.nodeInfoDecode),
("_ShapeInfo", self.shapeInfoDecode),
("_ShaderInfo", self.shaderInfoDecode)]
for placeholder, decoder in decoders:
if placeholder in obj:
return decoder(obj[placeholder])
else:
for k in obj:
obj[k] = self.recursiveDecode(obj[k])
elif isinstance(obj, list):
for x in range(len(obj)):
obj[x] = self.recursiveDecode(obj[x])
return obj
def setDecode(self, v):
return set(v)
def nodeInfoDecode(self, v):
o = NodeInfo()
o.update(self.recursiveDecode(v))
return o
def shapeInfoDecode(self, v):
o = ShapeInfo()
o.update(self.recursiveDecode(v))
return o
def shaderInfoDecode(self, v):
o = ShaderInfo()
o.update(self.recursiveDecode(v))
return o
The nodeInfoDecode methods gets the entered dictionary and uses it to initialize the values/attributes of the NodeInfo object that gets created and returned.
More info:
Also see my answer on How to change json encoding behaviour for serializable python object?