python对象的序列换与反序列化
Posted 雅虎跳跳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python对象的序列换与反序列化相关的知识,希望对你有一定的参考价值。
class Student: def __init__(self, id, name, sex) -> None: self.id = id self.name = name self.sex = sex
1、序列化。有s1 = Student(1001,‘ZhangSan‘,‘man‘),将s1序列化为json:
import json s_json = json.dumps(s1.__dict__)
2、反序列化。有s_json = ‘{“id”:“1001”, "name":"ZhangSan", "sex":"man"}’
解法一:反序列化,不同的类需要单独写一个反序列化的函数。对于Student类,如下:
class Student: def __init__(self, id, name, sex) -> None: self.id = id self.name = name self.sex = sex @staticmethod def convert_json_to_student(self, s_json): s_json = json.loads(s_json) return Student(s_json["id"], s_json["name"], s_json["sex"])
s1 = Student().convert_json_to_student(s_json)
或者
s1 = json.loads(s_json, object_hook=Student().convert_json_to_student)
解法二:写一个通用的反序列化类
class Json_to_object: def __init__(self, d) self.__dict__ = d def copy_properties(object1, object2): for i in object1.__dict__: object1.__dict__.[i] = object2.__dict__.get(i) if(object2.__dict__.get(i) else object1.__dict__.[i] s1 = json.loads(s_json, object_hook=Json_to_object)
以上是关于python对象的序列换与反序列化的主要内容,如果未能解决你的问题,请参考以下文章
21天学习python编程_pickle模块序列化与反序列化