内置json模块对于Python内置类型序列化的描述
"""Extensible JSON <http://json.org> encoder for Python data structures. Supports the following objects and types by default: +-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null | +-------------------+---------------+ To extend this to recognize other objects, subclass and implement a ``.default()`` method with another method that returns a serializable object for ``o`` if possible, otherwise it should call the superclass implementation (to raise ``TypeError``). """
内置json模块对于Python内置类型反序列化的描述
"""Simple JSON <http://json.org> decoder Performs the following translations in decoding by default: +---------------+-------------------+ | JSON | Python | +===============+===================+ | object | dict | +---------------+-------------------+ | array | list | +---------------+-------------------+ | string | str | +---------------+-------------------+ | number (int) | int | +---------------+-------------------+ | number (real) | float | +---------------+-------------------+ | true | True | +---------------+-------------------+ | false | False | +---------------+-------------------+ | null | None | +---------------+-------------------+ It also understands ``NaN``, ``Infinity``, and ``-Infinity`` as their corresponding ``float`` values, which is outside the JSON spec. """
分别使用pickle和json模块来实现自定义类型的序列化和反序列化
class Person(): """人类""" # __slots__ = ['age'] # __dict__ = ['age', 'name'] _age: int = 0 def __init__(self, age, name='eason'): # json.JSONEncoder.__init__(self, skipkeys=True) self.age = age self.name = name # self.name = name # def __dir__(self): # return ['age', 'name'] @property def age(self) -> int: return self._age @age.setter def age(self, age: int): print('set age') if age <= 0: raise ValueError('age') self._age = age def hello(self): print('==============hello-locals===============') print(locals())
import pickle import json from demo.src.models.person import Person # import demo.src.models.person.Person class PersonJSONEncoder(json.JSONEncoder): def default(self, o: Person): # 返回字典类型 return {"name": o.name, "age": o.age} # def encode(self, o: Person): # # 直接返回字典, # return str({"age": o.age, "name": o.name}) class PersonJSONDecoder(json.JSONDecoder): def decode(self, s: str): obj_dict = json.loads(s) # return Person(obj_dict['age'], obj_dict['age']) return Person(**obj_dict) p = Person(28, 'wjchi') # bytes # p_bytes = pickle.dumps(p) # print(type(p_bytes), p_bytes) # p_obj = pickle.loads(p_bytes) # print(type(p_obj), p_obj.age) # string # p_str = json.dumps(p, default=lambda obj: obj.__dict__) # print(type(p_str), p_str) # p_dict = json.loads(p_str) # print(type(p_dict), p_dict['age']) p_str = json.dumps(p, cls=PersonJSONEncoder) print(type(p_str), p_str) p_dict = json.loads(p_str) # print(type(p_dict), p_dict['age']) # p_obj = json.loads(p_str, cls=PersonJSONDecoder) p_obj = Person(**p_dict) print(type(p_obj), p_obj.age)