【发布时间】: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