天天看點

python 序列化類定義_Python 序列化/反序列化自定義類型

内置json子產品對于Python内置類型序列化的描述

"""Extensible JSON 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 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子產品來實作自定義類型的序列化和反序列化

classPerson():"""人類"""

#__slots__ = ['age']

#__dict__ = ['age', 'name']

_age: int =0def __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']

@propertydef age(self) ->int:returnself._age

@age.setterdefage(self, age: int):print('set age')if age <=0:raise ValueError('age')

self._age=agedefhello(self):print('==============hello-locals===============')print(locals())

importpickleimportjsonfrom demo.src.models.person importPerson#import demo.src.models.person.Person

classPersonJSONEncoder(json.JSONEncoder):defdefault(self, o: Person):#傳回字典類型

return {"name": o.name, "age": o.age}#def encode(self, o: Person):

## 直接傳回字典,

#return str({"age": o.age, "name": o.name})

classPersonJSONDecoder(json.JSONDecoder):defdecode(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)