1 Python类对象的json序列化和json反序列化

python类对象json序列化的定义:将类对象转换为可通过网络传输或可以存储到本地磁盘的Json数据格式的过程称为序列化;

python类对象json反序列化的定义:将Json转化为python类对象的过程称为反序列化;

2 jsonpickle库介绍

官方地址:http://jsonpickle.github.io/,关于该库的更多用法请参考官方文档。

2.1 jsonpickle安装

  • pip
pip install jsonpickle
  • conda
conda install jsonpickle

2.2 jsonpickle的使用

3 使用jsonpickle库对Python类对象序列化和反序列化

3.1 序列化

代码:

import jsonpickle

class RequestArgs:
    def __init__(self,name,video_path):
        self.name = name
        self.video_path = video_path


class RequestApi:
    def __init__(self, funcode, token, reqeuestargs_object):
        self.funcode = funcode
        self.token = token
        self.args = reqeuestargs_object


if __name__ == '__main__':
    requestApi = RequestApi('101101','2ec45770-b897-4cd0-8ae1-e65ab065a661',RequestArgs('liming','liming.mp4'))

    john_string = jsonpickle.encode(requestApi,unpicklable=False)

    print(john_string)

序列化结果:

{
    "funcode": "101101", 
    "token": "2ec45770-b897-4cd0-8ae1-e65ab065a661", 
    "args": {
        "name": "liming", 
        "video_path": "liming.mp4"
    }
}

3.2 反序列化

import jsonpickle

class RequestArgs:
    def __init__(self,name,video_path):
        self.name = name
        self.video_path = video_path


class RequestApi:
    def __init__(self, funcode, token, reqeuestargs_object):
        self.funcode = funcode
        self.token = token
        self.args = reqeuestargs_object


if __name__ == '__main__':
    json_str = '{"funcode": "101101", "token": "2ec45770-b897-4cd0-8ae1-e65ab065a661", "args": {"name": "liming", "video_path": "liming.mp4"}}'
    requestApi_dict = jsonpickle.decode(json_str)

    requestApi = RequestApi(requestApi_dict['funcode'],requestApi_dict['token'],RequestArgs(requestApi_dict['args']['name'],requestApi_dict['args']['video_path']))

    print(requestApi.funcode)
    print(requestApi.token)
    print(requestApi.args.name)
    print(requestApi.args.video_path)

结果:

101101
2ec45770-b897-4cd0-8ae1-e65ab065a661
liming
liming.mp4