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