I've set up some classes of my own that are subclassed from a dictionary to act like them. Yet when I want to encode them to JSON (using Python) I want them to be serialized in a way that I can decode them back to the original objects instead of to a dict.
So I want to support nested objects of my own classes (that are inherited from dict).
I had tried stuff like:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if type(o).__name__ == "NodeInfo":
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShapeInfo":
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif type(o).__name__ == "ShaderInfo":
return '{"_ShaderInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
return super(ShadingInfoEncoder, self).encode(o)
And:
class ShadingInfoEncoder(json.JSONEncoder):
def encode(self, o):
if isinstance(o, NodeInfo):
return '{"_NodeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShapeInfo):
return '{"_ShapeInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
elif isinstance(o, ShaderInfo):
return '{"_ShaderInfo": ' + super(ShadingInfoEncoder, self).encode(o) + '}'
return super(ShadingInfoEncoder, self).encode(o)
It works in general, yet not when they are nested or the first object getting dumped is not of those types. Thus this only works when the input object is of that type. Yet not when it's nested.
I'm not sure how to encode this JSON recursively so all nested/contained instances are encoded according to the same rules.
I thought it would be easier to the use the JSONEncoder's default method (as that gets called whenever an object is of an unsupported type.) Yet since my objects are inherited from dict they get parsed to dictionaries instead of being process by the 'default' method.