1 python不依赖第三方库对类对象进行json序列化与反序列化
import json
class RequestArgs:
def __init__(self,name,video_path):
self.name = name
self.video_path = video_path
@staticmethod
def fromJson(mapping):
if mapping is None:
return None
return RequestArgs(name=mapping.get('name'),video_path=mapping.get('video_path'))
class RequestApi:
def __init__(self, funcode, token, reqeuestargs_object):
self.funcode = funcode
self.token = token
self.args = reqeuestargs_object
@staticmethod
def fromJson(mapping):
if mapping is None:
return None
return RequestApi(funcode=mapping.get('funcode'),token=mapping.get('token'),reqeuestargs_object=RequestArgs.fromJson(mapping.get('args')))
# 将类对象序列化
def obj_serialization_to_json(obj, **kwargs):
return json.dumps(obj, default=lambda j: j.__dict__, **kwargs)
# 将json反序列化为对象
def json_deserialization_to_obj(msg, cls, **kwargs):
return cls.fromJson(json.loads(msg, **kwargs))
if __name__ == '__main__':
requestApi = RequestApi('101101', '2ec45770-b897-4cd0-8ae1-e65ab065a661', RequestArgs('liming', 'liming.mp4'))
# 序列化
requestApi_json_str = obj_serialization_to_json(requestApi)
print('类对象序列化结果:\n'+requestApi_json_str)
# 反序列化
requestApi_deserialize = json_deserialization_to_obj(requestApi_json_str,RequestApi)
print('json反序列化结果:')
print(requestApi_deserialize.funcode)
print(requestApi_deserialize.token)
print(requestApi_deserialize.args.name)
print(requestApi_deserialize.args.video_path)
代码执行结果:
类对象序列化结果:
{"funcode": "101101", "token": "2ec45770-b897-4cd0-8ae1-e65ab065a661", "args": {"name": "liming", "video_path": "liming.mp4"}}
json反序列化结果:
101101
2ec45770-b897-4cd0-8ae1-e65ab065a661
liming
liming.mp4
本文作者:StubbornHuang
版权声明:本文为站长原创文章,如果转载请注明原文链接!
原文标题:Python – 不依赖第三方库对类对象进行json序列化与反序列化
原文链接:https://www.stubbornhuang.com/1470/
发布于:2021年07月30日 15:54:09
修改于:2023年06月26日 21:24:39
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
评论
50