我已经设置了一些我自己的类,它们是从字典子类化的,以像它们一样工作。然而,当我想将它们编码为JSON(使用Python)时,我希望它们以一种我可以将它们解码回原始对象而不是字典的方式进行序列化。
所以我想支持我自己类的嵌套对象(继承自dict)
我试过这样的东西:
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)
:
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)
通常可以工作,但当它们嵌套或第一个被转储的对象不是这些类型时就不行。因此,这仅在输入对象为该类型时才有效。然而,当它嵌套时却不是。
我不知道如何递归地编码这个JSON,所以所有嵌套/包含的实例都按照相同的规则编码。
我认为使用JSONEncoder的默认方法会更容易(因为每当对象是不支持的类型时就会调用该方法)。然而,由于我的对象继承自dict,它们被解析为字典,而不是由'default'方法处理。
最后我做了如下的事情:
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
我认为这不是最好的方法,但我在这里分享它,看看是否有人能告诉我我做错了什么,并告诉我最好的方法!
请注意,我使用嵌套元组而不是字典,因为我想保持它们列出的顺序,这样我就可以-在这个例子中-重写ShaderInfo成为_NodeInfo如果ShaderInfo是从NodeInfo继承的对象。
我的解码器设置为沿着(简化和部分代码)行做一些事情:
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
nodeInfoDecode方法获取输入的字典,并使用它来初始化创建和返回的NodeInfo对象的值/属性。
更多信息:
也看到我的回答如何改变json编码行为序列化python对象?