如何使对象自行序列化?

时间:2017-03-03 10:58:27

标签: python python-3.x

如何使对象可序列化?以下代码:

# -*- coding: utf-8 -*-
import json
import pickle
import bson


class A(object):
    def __init__(self):
        self.a = 'a'

    def __reduce__(self):
        return type(self), (self.a,)

try:
    print(pickle.dumps({'a': A()}))  # Ok
except Exception as exc:
    print(exc)

try:
    print(json.dumps({'a': A()}))  # Error
except Exception as exc:
    print(exc)

try:
    print(bson.BSON.encode({'a': A()}))  # Error
except Exception as exc:
    print(exc)

产生

b'\x80\x03}q\x00X\x01\x00\x00\x00aq\x01c__main__\nA\nq\x02h\x01\x85q\x03Rq\x04s.'
<__main__.A object at 0x7f3a06fef048> is not JSON serializable
Cannot encode object: <__main__.A object at 0x7f3a06fef048>

我不想编写自己的JSON,BSON等序列化程序,我需要自己制作对象json / bson / ...序列化。

有可能吗?怎么样?

0 个答案:

没有答案