覆盖继承的默认支持对象(如dict,list)的嵌套JSON编码

时间:2013-05-03 14:24:49

标签: python json encoding recursion nested

我已经设置了一些我自己的类,这些类是从字典创建的子类,就像它们一样。然而,当我想将它们编码为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继承的,因此它们被解析为字典而不是由默认'处理方法

1 个答案:

答案 0 :(得分:1)

我最终做了以下事情。

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对象的值/属性。

更多信息:

另见How to change json encoding behaviour for serializable python object?

的答案
相关问题