序列号与反序列化

对象序列化

import json

class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score
def student2dict(std):
    return {
        'name': std.name,
        'age': std.age,
        'score': std.score
    }
s = Student('Bob', 20, 88)
# print(json.dumps(s))
print(json.dumps(s, default=student2dict))
print(json.dumps(s, default=lambda obj: obj.__dict__))

对象反序列化:

import json

class JSONObject:

  def __init__(self, d):

​    self.__dict__ = d 



json_string='{"name":"kevin","age":30}'

obj=json.loads(json_string,object_hook=JSONObject)

print(obj.name)

print(obj.age)

你可能感兴趣的:(序列号与反序列化)