【问题标题】:Django Rest Framework Response is not JSON serializable errorDjango Rest Framework Response 不是 JSON 可序列化错误
【发布时间】:2017-10-11 10:21:27
【问题描述】:

我在 Django REST 框架中有以下自定义异常处理程序。

class ErrorMessage:
    def __init__(self, message):
        self.message = message

def insta_exception_handler(exc, context):
    response = {}

    if isinstance(exc, ValidationError):
        response['success'] = False
        response['data'] = ErrorMessage("Validation error")

    return Response(response)

我想要一个如下所示的 JSON 输出

"success":false,
"data":{ "message" : "Validation error" }

但我收到错误 TypeError: Object of type 'ErrorMessage' is not JSON serializable。为什么像上面 ErrorMessage 这样简单的类不能 JSON 序列化?我该如何解决这个问题?

【问题讨论】:

  • 您将ErrorMessage 对象分配给response['data']。类对象不能神奇地更改为 python dict。检查此链接:stackoverflow.com/questions/61517/… 用于将 python 类对象转换为 dict。

标签: python django python-3.x django-rest-framework


【解决方案1】:

我认为更通用的方法是创建一个序列化程序来序列化错误消息对象:

from rest_framework import serializers

class ErrorMessageSerializer(serializers.Serializer):
    message = serializers.CharField(max_length=256)

那么你可以这样做:

def insta_exception_handler(exc, context):
    ...
    serializer = ErrorMessageSerializer(ErrorMessage("Validation error"))
    response["data"] = serializer.data
    ...

【讨论】:

    【解决方案2】:

    它不可序列化,因为它是object,它应该是dictlist 或普通值。但是您可以使用魔术属性__dict__ 轻松解决您的问题

    def insta_exception_handler(exc, context):
        response = {}
    
        if isinstance(exc, ValidationError):
            response['success'] = False
            # like this
            response['data'] = ErrorMessage("Validation error").__dict__
    
        return Response(response)
    

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 1970-01-01
      • 2022-07-01
      • 2023-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      • 2016-05-07
      • 2019-05-23
      相关资源
      最近更新 更多