import json
import functools
# json->object 映射函數(shù)(不支持函數(shù)方法成員)
def __praseObject(jsonStr, Class):
"""Class needs a constructor with no arguments"""
data = json.loads(jsonStr)
result = Class()
result.__dict__ = data
return result
# 綁定函數(shù)
json.fromObject = functools.partial(json.dumps, default=lambda obj: obj.__dict__)
json.toObject = __praseObject
# Example code
class Student(object):
def __init__(self, name="", age=0):
super().__init__()
self.name = name
self.age = age
student = Student("wavky", 18)
jsonStr = json.fromObject(student) # student -> json
newStudent = json.toObject(jsonStr, Student) # json -> student