2013-07-24 49 views
4

X是一個簡單的類與3個字段:JSON(反)序列爲嵌套類

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

Y類具有X爲AA值字段內的字典:

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

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

JSON編碼器/解碼器Y的外觀如何?

+2

我打賭美元甜甜圈一個理智的JSON庫可以直接編碼字典。 – millimoose

+0

和解碼多少? –

+0

你**已經**從解碼器中取回字典。 (你可能必須映射它們並用類似'self.m = {k:XDecoder()。decode(v)for k,v in super()。decode(json_string)} ['m']的值解碼值。項目()') – millimoose

回答

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