JSON(de)序列化嵌套类

时间:2013-07-24 15:22:09

标签: python json

X是一个包含3个字段的简单类:

class X():
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

X的JSON编码器/解码器:

class XEncoder(json.JSONEncoder):
    def encode(self, obj):
        return super(XEncoder, self).encode({
            'a': obj.a,
            'b': obj.b,
            'c': obj.c
        })

class XDecoder(json.JSONDecoder):
    def decode(self, json_string):
        obj = super(XDecoder, self).decode(json_string)
        return X(obj['a'], obj['b'], obj['c'])

Y类,其中X作为字段内dict的值:

class Y():
    def __init__(self):
        self.m = {}

    def add(self, a, x):
        self.m[a] = x

Y的JSON编码器/解码器如何显示?

1 个答案:

答案 0 :(得分:1)

class YEncoder(json.JSONEncoder):
    def encode(self, obj):
        return json.dumps({ 'm': json.dumps({ k: json.dumps(v, cls=XEncoder) for k, v in obj.m.items()})})

class YDecoder(json.JSONDecoder):
    def decode(self, json_string):
        y.m = {k: json.loads(v, cls=XDecoder) for k, v in json.loads(json.loads(json_string)['m']).items()}
        return y