Python json序列化时default/object_hook指定函数处理

在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)
posted @ 2017-02-09 11:54  ccorz  阅读(8294)  评论(0编辑  收藏  举报