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

这篇博客介绍了如何在Python中将自定义类的对象转换为JSON字符串。通过使用__dict__属性,将类实例转化为字典,然后利用json.dumps()方法进行序列化。示例中展示了ReportBean、ReportResultBean和ReportResultDetailBean三个类的实例转化过程,最终将整个数据结构转换为JSON格式并打印出来。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

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

Report.py

class ReportBean:
    def __init__(self, channel, version, result):
        self.channel = channel
        self.version = version
        self.result = result


class ReportResultBean:
    def __init__(self, success, fail, total, startType, detail):
        self.success = success
        self.fail = fail
        self.total = total
        self.startType = startType
        self.detail = detail


class ReportResultDetailBean:
    def __init__(self, component, success):
        self.component = component
        self.success = success

TestJson.py

import json

from bean.Report import ReportResultBean, ReportResultDetailBean, ReportBean

bean = 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}]}}

格式化后如下所示:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值