Python 之 Json序列化嵌套类

想要用python自已手动序列化嵌套类,就要明白两个问题:

1.Json是什么?

2.Json支持什么类型?

 

答案显而易见

Json就是嵌套对象

Json在python中支持列表,字典(当然也支持int,string.....,不过说这个也没多大必要)

 

很好,等等,列表,字典?我们在python中学过列表,字典,字典列表,列表字典,字典字典,那,我们可不可以把类对象转化为这些呢?

我可以很确定的告诉你,可以,并且,嵌套类都可以!!!

下面就来实战:

 

from flask import Flask
import json

app = Flask(__name__)

class City():
    def __init__(self,country,provider):
        self.country = country
        self.provider = provider


class School():
    def __init__(self,country,provider,name,nums):
        self.city = City(country,provider)
        self.name = name
        self.nums = nums


@app.route('/method0')
def method0():
    school = School('china','shanxi','wutaizhongxue','2000')

    s_temp0 = [school.city.country,school.city.provider,school.name,school.nums]
    return json.dumps(s_temp0)


@app.route('/method1')
def method1():
    school = School('china','shanxi','wutaizhongxue','2000')

    s_temp1 = {'country':school.city.country,'provider':school.city.provider,'name':school.name,'nums':school.nums}
    return json.dumps(s_temp1)


@app.route('/method2')
def method2():
    school = School('china','shanxi','wutaizhongxue','2000')

    s_temp2 = [{'country':school.city.country,'provider':school.city.provider},school.name,school.nums]
    return json.dumps(s_temp2)


@app.route('/method3')
def method3():
    school = School('china','shanxi','wutaizhongxue','2000')

    s_temp3 = {'city':[school.city.country,school.city.provider],'name':school.name,'nums':school.nums}
    return json.dumps(s_temp3)


@app.route('/method4')
def method4():
    school = School('china','shanxi','wutaizhongxue','2000')

    s_temp4 = {'city':{'country':school.city.country,'provider':school.city.provider},'name':school.name,'nums':school.nums}
    return json.dumps(s_temp4)


if __name__ == '__main__':
    app.run(debug=True)

 

执行效果:

 

很多人会说,第五种才是我想要的,前面四种不是标准的json数据,刚开始确实是这样认为的,但是。。。

1.如果你处理的两个嵌套类是数据库的呢?假比如一对多的关系型数据库,method3不是一个很好的选择么?

2.如果你处理的两个嵌套类是包含关系呢?method2不是一个很好的选择么?

。。。。。。

多说无益,需要你自己体会

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT蓝月

谢谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值