4

X是一个具有 3 个字段的简单类:

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

JSON编码器/解码器X

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'])

YX在字段中具有 dict 值的类:

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

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

JSON 编码器/解码器的Y外观如何?

4

1 回答 1

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
于 2013-07-24T22:58:46.380 回答