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

如果您觉得对您有帮助,可以请站长喝一杯咖啡哦!

记得在赞赏备注里写上您的昵称

您可在本站资助名单中查看你的打赏记录哦!

支付宝扫一扫

微信扫一扫

金额随意,礼清义重

当前分类随机文章推荐

全站随机文章推荐

关于本站站长 StubbornHuang
Python – 使用jsonpickle库对Python类对象进行json序列化和json反序列化操作-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。