码迷,mamicode.com
首页 > 编程语言 > 详细

python对象的序列换与反序列化

时间:2020-04-19 23:42:13      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:stat   不同的   turn   else   反序   one   imp   copy   none   

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对象的序列换与反序列化

标签:stat   不同的   turn   else   反序   one   imp   copy   none   

原文地址:https://www.cnblogs.com/yahutiaotiao/p/12735059.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!