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序列化与反序列化-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。