Django2 序列化(json + xml)

哈哈 阅读:624 2021-03-31 18:17:29 评论:0

第一步:创建json 序列化工具类:JSONUtil.py

import json 
from django.core.serializers import serialize, deserialize 
from django.db import models 
from django.http import JsonResponse 
 
 
# json 序列化 
def json_to_list(json): 
    if json[0] == '[': 
        deserializedObjectList = deserialize('json', json) 
    else: 
        deserializedObjectList = deserialize('json', '[' + json + ']') 
    list = [] 
    for deserializedObject in deserializedObjectList: 
        list.append(deserializedObject.object) 
    return list 
 
 
# 序列化 
def to_json(obj): 
    if isinstance(obj, models.Model): 
        obj = [obj]  # 因为serialize只支持可迭代对象,比如querySet对象 
    data = serialize("json", obj) 
    return data 
 
 
# 该方法没有做严格的验证,只支持dict,models.Model,models.QuerySet,可以根据需要自行扩展 
def render_json(data, dict_key='data', **response_kwargs): 
    if isinstance(data, dict): 
        return JsonResponse(data) 
    data = to_json(data) 
    if 'safe' in response_kwargs and response_kwargs['safe'] is False: 
        pass 
    else: 
        data = {dict_key: data}  # 默认必须传递字典数据 
    if isinstance(data, str):  # 由于非字典类型的数据会被当做字符串处理,即返回结果两边都有引号,所以此处将其转换为对象,否则ajax调用时不方便处理 
        data = json.loads(data) 
    return JsonResponse(data, **response_kwargs) 

第二步:创建XML 序列化工具类:XMLUtil.py

# -*- coding=utf-8 -*- 
from django.core import serializers 
from django.db import models 
from django.db.models.query import QuerySet 
from django.http import HttpResponse 
 
 
def render_xml(data): 
    data = to_xml(data) 
    response = HttpResponse(data) 
    response['Content-Type'] = 'application/xml' 
    return response 
 
 
# 序列化 
def to_xml(data): 
    if isinstance(data, models.Model): 
        data = [data]  # 因为serialize只支持可迭代对象,比如querySet对象 
    elif isinstance(data, QuerySet): 
        data = data 
    else: 
        pass 
    data = serializers.serialize("xml", data) 
    return data 
 
 
# 反序列化 
def xml_to_list(xml): 
    deserializedObjectList = serializers.deserialize("xml", xml) 
    list = [] 
    for deserializedObject in deserializedObjectList: 
        list.append(deserializedObject.object) 
    return list 

视图函数编写:

# json 序列化 
def json(request): 
    book_list = Books.objects.all() 
    return JSONUtil.render_json(book_list, safe=False) 
 
 
# xml 序列化 
def xml(request): 
    book_list = Books.objects.all() 
    return XMLUtil.render_xml(book_list)

路由函数:

from django.conf.urls import url 
from . import views 
 
urlpatterns = [ 
    url('create/', views.create, name='create'), 
    url('read', views.read, name='read'), 
    url('update/', views.update, name='update'), 
    url('delete/', views.delete, name='delete'), 
    url('search', views.search, name='search'), 
    url('json/', views.json), 
    url('xml/', views.xml), 
] 

效果展示:

标签:Django
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号