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)

 

相关推荐