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)
相关推荐
Lzs 2020-10-23
xclxcl 2020-08-03
zmzmmf 2020-08-03
葫芦小金刚 2020-07-22
ericdoug 2020-07-18
Erick 2020-06-17
aanndd 2020-06-16
Erick 2020-06-17
aanndd 2020-06-16
xuebingnan 2020-06-13
80337960 2020-06-10
Jerry 2020-06-01
mengdg000 2020-05-29
spring-data-redis RedisTemplate 操作redis时发现存储在redis中的key不是设置的string值,前面还多出了许多类似\xac\xed\x00\x05t\x00;
尹小鱼 2020-05-29
somebodyoneday 2020-05-15
visionzheng 2020-05-05
visionzheng 2020-05-04
igogo00 2020-05-03