Tom Finet
Tom Finet

Reputation: 2136

How to return list of django model instances as JSON?

I have a view:

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")

This gives me the following in 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}}"
]

On the android client side when making a request to this view the following error occurs:

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

I think this means there shouldn't be any " wrapping the JSON response. If this is the problem how do I remove them? If this is not the problem how do I fix this?

Upvotes: 0

Views: 2960

Answers (1)

Rajan Chauhan
Rajan Chauhan

Reputation: 1375

A better way to do this would be to create a serializer for your Friend model and using that serializer class to convert it to JSON. But if you don't want to use that this will give you the near solution to what you are trying

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 method is serializing the Django objects and convert them into a representational string. As we know that the string should be a JSON representation we converted the string to JSON sent it as JSONResponse. Refer this

Upvotes: 1

Related Questions