在Python中,json.dumps
函數接受參數default
用於指定一個函數,該函數能夠把自定義類型的對象轉換成可序列化的基本類型。json.loads
函數接受參數objec_thook
用於指定函數,該函數負責把反序列化后的基本類型對象轉換成自定義類型的對象。
boy1 = boy('Will', 20)
#default method for decode
def boydefault(obj):
if isinstance(obj, boy):
return {'name': obj.name, 'age': obj.age}
return obj;
def boyhook(dic):
print('test')
if dic['name']:
return boy(dic['name'], dic['age'])
return dic
boy_encode_str = json.dumps(boy1, default=boydefault)
new_boy = json.loads(boy_encode_str, object_hook=boyhook)
print(boy_encode_str)
print(new_boy)