简体   繁体   中英

How to return a model instance as JSON to be deserialized by GSON android side?

I have a django rest framework GenericAPIView :

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

    def get(self, request, format=None):
        friendship_requests_list = Friend.objects.unread_requests(user=request.user)
        friendship_requets_dict = [friend_request_as_json(obj) for obj in friendship_requests_list]
        return Response(json.dumps(friendship_requets_dict), content_type="application/json")

ListUnseenFriendRequests should return a list of all the friends of the user making the request. I am not sure if this is the best/easiest way to return a FriendshipRequest object as json , if there is a better way please tell me.

I also use 2 helper methods, friend_request_as_json and user_as_json :

def friend_request_as_json(obj):
    return dict(
        id=obj.id, 
        from_user=user_as_json(obj.from_user), 
        created=str(obj.created))

def user_as_json(obj):
    return dict(
        id=obj.id,
        email=obj.email,
        firstName=obj.firstName,
        lastName=obj.lastName)

Testing the ListUnseenFriendRequests view using postman this is what I get:

"[{\"created\": \"2017-08-02 09:06:54.272168+00:00\", \"id\": 29, 
\"from_user\": {\"lastName\": \"Graham\", \"email\": \"joe@gmail.com\", \"firstName\": \"Joe\", \"id\": 5}}]"

Why are there all these backslashes? Does it make a difference?

On the client side, I use retrofit and GSON to deserialize for me. The model on the client side that will hold this response data is FriendRequestResponse :

public class FriendRequestResponse {

    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("from_user")
    @Expose
    private User fromUser;

    @SerializedName("created")
    @Expose
    private String createdAt;

    public FriendRequestResponse(int id, User fromUser, String createdAt) {
        this.id = id;
        this.fromUser = fromUser;
        this.createdAt = createdAt;
    }

    public int getId() {
        return id;
    }

    public User getFromUser() {
        return fromUser;
    }

    public String getCreatedAt() {
        return createdAt;
    }
}

The User model:

public class User {

    @SerializedName("id")
    @Expose
    private int id;

    @SerializedName("email")
    @Expose
    private String email;

    @SerializedName("firstName")
    @Expose
    private String firstName;

    @SerializedName("lastName")
    @Expose
    private String lastName;

    @SerializedName("date_joined")
    @Expose
    private String dateJoined;

    private String password;

    public User(String email, String firstName, String lastName, String password) {
        this.email = email;
        this.firstName = firstName;
        this.lastName = lastName;
        this.password = password;
    }

    public int getId() { return id; }

    public String getEmail() {
        return email;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String getPassword() {
        return password;
    }

    public String getDateJoined() {
        return dateJoined;
    }
}

Is this model correctly structured to take the json and fit it?

You already have JSON, which you are trying to dump as JSON.

Try using the following instead:

return Response(json.loads(friendship_requets_dict), content_type="application/json")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM