python对象的序列换与反序列化
2021-02-11 18:19
标签:stat 不同的 turn else 反序 one imp copy none 1、序列化。有s1 = Student(1001,‘ZhangSan‘,‘man‘),将s1序列化为json: 2、反序列化。有s_json = ‘{“id”:“1001”, "name":"ZhangSan", "sex":"man"}’ 解法一:反序列化,不同的类需要单独写一个反序列化的函数。对于Student类,如下: s1 = Student().convert_json_to_student(s_json) 或者 s1 = json.loads(s_json, object_hook=Student().convert_json_to_student) 解法二:写一个通用的反序列化类 python对象的序列换与反序列化 标签:stat 不同的 turn else 反序 one imp copy none 原文地址:https://www.cnblogs.com/yahutiaotiao/p/12735059.htmlclass Student:
def __init__(self, id, name, sex) -> None:
self.id = id
self.name = name
self.sex = sex
import json
s_json = json.dumps(s1.__dict__)
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"])
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)