1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Python 自定义对象数组 转JSON 字符串

Python 自定义对象数组 转JSON 字符串

时间:2024-02-27 11:07:29

相关推荐

Python 自定义对象数组 转JSON 字符串

前言

在Python中基本数据类型可以直接使用json.dumps直接转json字符串,但是对于自定义的类来说,需要先将对象“字典化”,也就是使用__dict__这个函数;同理对于数组中的对象,每个对象都需要提前“字典化”,废话不多说,看代码:

Report.py

class ReportBean:def __init__(self, channel, version, result):self.channel = channelself.version = versionself.result = resultclass ReportResultBean:def __init__(self, success, fail, total, startType, detail):self.success = successself.fail = failself.total = totalself.startType = startTypeself.detail = detailclass ReportResultDetailBean:def __init__(self, component, success):ponent = componentself.success = success

TestJson.py

import jsonfrom bean.Report import ReportResultBean, ReportResultDetailBean, ReportBeanbean = ReportResultDetailBean("com.onexzgj.Activity1", True).__dict__bean1 = ReportResultDetailBean("com.onexzgj.Activity2", False).__dict__details = []details.append(bean)details.append(bean1)resultBean = ReportResultBean(100, 50, 150, "上架", details).__dict__reportBean = ReportBean("应用宝", "第10000个版本", resultBean).__dict__data2 = json.dumps(reportBean)print(data2)

运行结果:

{"channel": "\u5e94\u7528\u5b9d", "version": "\u7b2c10000\u4e2a\u7248\u672c", "result": {"success": 100, "fail": 50, "total": 150, "startType": "\u4e0a\u67b6", "detail": [{"component": "com.onexzgj.Activity1", "success": true}, {"component": "com.onexzgj.Activity2", "success": false}]}}

格式化后如下所示:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。