189 8069 5689

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)

分享文章:Python之Json序列化嵌套类方式-创新互联
网站地址:http://cdxtjz.cn/article/csjceo.html

其他资讯