重写继承的默认支持对象(如dict、lis)的嵌套JSON编码

2024-10-01 13:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经建立了一些自己的类,这些类是从字典中派生出来的类来表现的。然而,当我想将它们编码为JSON(使用Python)时,我希望它们以一种可以将它们解码回原始对象而不是dict的方式序列化

所以我想支持我自己类的嵌套对象(继承自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)

以及:

^{pr2}$

一般来说,当它们被嵌套或者第一个被转储的对象不是这些类型时,它就不起作用了。因此,只有当输入对象是该类型时,这才有效。但当它被嵌套时就不会了。在

我不知道如何递归地编码这个JSON,所以所有嵌套/包含的实例都是根据相同的规则编码的。在

我原以为使用JSONEncoder的默认方法会更容易(每当对象是不受支持的类型时都会调用该方法),但是由于我的对象是从dict继承的,所以它们被解析为字典,而不是被“default”方法处理。在


Tags: 对象方法nameselfjson类型编码return
1条回答
网友
1楼 · 发布于 2024-10-01 13:33:39

最后我做了以下事情。在

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。在

我的译码器被设置为按照(简化和部分代码)的思路执行某些操作:

^{pr2}$

nodeInfoDecode方法获取输入的字典,并使用它初始化创建和返回的NodeInfo对象的值/属性。在

更多信息:

另请参阅我在How to change json encoding behaviour for serializable python object?上的回答

相关问题 更多 >