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编码器/解码器如何显示?
答案 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