Python: 自定义类对象序列化为Json串

    之前已经实现了Python: Json串反序列化为自定义类对象,这次来实现了Json的序列化。

    测试代码和结果如下:

import Json.JsonTool


class Score:
    math = 0
    chinese = 0


class Book:
    name = ''
    type = ''


class Student:
    id = ''
    name = ''
    score = Score()
    books = [Book()]


student = Student()

json_data = '{"id":"123", "name":"kid", "score":{"math":100, "chinese":98}, ' \
            '"books":[{"name":"math", "type":"study"}, ' \
            '{"name":"The Little Prince", "type":"literature"}]} '
Json.JsonTool.json_deserialize(json_data, student)

print(student.name)
print(student.score.math)
print(student.books[1].name)

student_str = Json.JsonTool.json_serialize(student)
print(student_str)

input("\n按回车键退出。")

运行结果:

kid
100
The Little Prince
{"books": [{"name": "math", "type": "study"}, {"name": "The Little Prince", "type": "literature"}], "id": "123", "name": "kid", "score": {"chinese": 98, "math": 100}}

按回车键退出。

 

    实现代码如下:

def json_serialize(obj):
    obj_dic = class2dic(obj)
    return json.dumps(obj_dic)


def class2dic(obj):
    obj_dic = obj.__dict__
    for key in obj_dic.keys():
        value = obj_dic[key]
        obj_dic[key] = value2py_data(value)
    return obj_dic


def value2py_data(value):
    if str(type(value)).__contains__('.'):
        # value 为自定义类
        value = class2dic(value)
    elif str(type(value)) == "<class 'list'>":
        # value 为列表
        for index in range(0, value.__len__()):
            value[index] = value2py_data(value[index])
    return value

 

转载于:https://www.cnblogs.com/magic8sky/p/10482073.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值