如何将django模型实例列表作为JSON返回?

时间:2017-08-02 11:01:48

标签: python json django-models django-views django-rest-framework

我有一个观点:

class ListUnseenFriendRequests(generics.GenericAPIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        friendship_requests_list = Friend.objects.unread_requests(user=request.user)
        friendship_requests_rough_json = [serializers.serialize('json', [obj]) for obj in friendship_requests_list]
        friendship_requests_json = [obj.strip("[]") for obj in friendship_requests_rough_json]
        return Response(friendship_requests_json, content_type="application/json")

这给了我以下JSON:

[
    "{\"model\": \"friendship.friendshiprequest\", \"pk\": 8, \"fields\": {\"from_user\": 6, \"to_user\": 4, \"message\": \"\", \"created\": \"2017-07-27T14:02:28.492Z\", \"rejected\": null, \"viewed\": null}}",
    "{\"model\": \"friendship.friendshiprequest\", \"pk\": 13, \"fields\": {\"from_user\": 2, \"to_user\": 4, \"message\": \"\", \"created\": \"2017-07-27T16:47:24.863Z\", \"rejected\": null, \"viewed\": null}}",
    "{\"model\": \"friendship.friendshiprequest\", \"pk\": 20, \"fields\": {\"from_user\": 14, \"to_user\": 4, \"message\": \"\", \"created\": \"2017-07-31T08:03:27.887Z\", \"rejected\": null, \"viewed\": null}}",
    "{\"model\": \"friendship.friendshiprequest\", \"pk\": 22, \"fields\": {\"from_user\": 22, \"to_user\": 4, \"message\": \"\", \"created\": \"2017-08-01T11:52:08.830Z\", \"rejected\": null, \"viewed\": null}}"
]

在对此视图发出请求时,在Android客户端,发生以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $[0]

我认为这意味着不应该有任何"包装JSON响应。如果这是问题,我该如何删除它们?如果这不是问题,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

更好的方法是为您的Friend模型创建一个序列化程序,并使用该序列化程序类将其转换为JSON。 但是,如果你不想使用它,这将为你提供接近你正在尝试的解决方案

from django.http import JsonResponse
import json
class ListUnseenFriendRequests(generics.GenericAPIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        friendship_requests_list = json.loads(serializers.serialize('json',Friend.objects.unread_requests(user=request.user))
        return JSONResponse(friendship_requests_list,safe=False)

serializers.serialize方法正在序列化Django对象并将它们转换为代表性字符串。我们知道字符串应该是JSON表示,我们将字符串转换为JSON,将其发送为JSONResponse。 请参阅this