当前位置: 移动技术网 > IT编程>脚本编程>Python > Python: Json串反序列化为自定义类对象

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

2019年03月07日  | 移动技术网IT编程  | 我要评论

宁波旅游团,背着你歌词,山东省三本院校排名

    之前已经实现了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

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网