一、简单json对象映射到class对象:
class Response:
""" 响应体response对象映射到class对象 """
def __init__(self):
self.success = None
self.code = None
self.traceId = None
self.data = None
def json_to_obj(self, json_str):
data = json.loads(json_str)
self.__dict__ = data
return self
if __name__ == '__main__':
string = b'{"success":true,"code":200,"traceId":"f60b2cb681c14a688dc99b21bb7f560f","data":{"id":"641420bcb299495df2b34b68"}}'
res = Response()
res.json_to_obj(string)
print("res:", res.__dict__)
print("Response:", Response.__dict__)
二、嵌套json对象映射到嵌套class对象:
class Response:
""" 响应体response对象映射到class对象 """
def __init__(self):
self.success = None
self.code = None
self.traceId = None
self.data = Data()
def json_to_obj(self, json_str):
string = json.loads(json_str)
self.data.__dict__ = string["data"]
# self.__dict__ = string
for key, value in string.items():
if key == "data":
self.data.__dict__ = value
else:
self.__dict__[key] = value
return self
class Data:
def __int__(self):
self.id = None
self.key = None
def __str__(self):
return {"id": self.id, "key": self.key}
if __name__ == '__main__':
string = b'{"success":true,"code":200,"traceId":"f60b2cb681c14a688dc99b21bb7f560f","data":{"id":"641420bcb299495df2b34b68", "key": "value"}}'
res = Response()
res.json_to_obj(string)
print("res:", res.__dict__)
print(f"res.data.id: {res.data.id}, type: {type(res.data)}")
# print("Response:", Response.__dict__)