0

I'm running a Python Back-End with an Android client in Java. I'm trying to return a JSON response to a request that I'm receiving. I've had previous issues with this, as my request has objects within objects but that was solved using a custom Encoder. Now, when I return my response after using json.dumps(), my Java client, parses it through GSON but it's invalid

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

When printing the response out in the console I get:

{"user": {"firstName": "Bob", "lastName": "Miller", "username": "bobbyboi", "profileImage": "image"}, "authToken": {"authToken": "authtoken", "dateTime": "time"}}

which looks correct, but not for GSON. It ends up coming in as

"{"user": {"firstName": "Bob", "lastName": "Miller", "username": "bobbyboi", "profileImage": "image"}, "authToken": {"authToken": "authtoken", "dateTime": "time"}}"

with the extra apostrophes at the end.

Here is my python code:

        dummyUser = User("Bob", "Miller", "bobbyboi", "image")
        dummyAuth = AuthToken("authtoken", "time")
        response = LoginResponse(dummyUser, dummyAuth)
        return json.dumps(response, cls=MyEncoder)

And the encoder, just in case that's the issue:

class MyEncoder(json.JSONEncoder):
    def default(self, o):
        if hasattr(o, "encode"):
            return o.encode()
        else:
            return json.JSONEncoder.default(self,o)

And then the Java GSON:

    if (http.getResponseCode() == HttpURLConnection.HTTP_OK){
           InputStream inputStream = http.getInputStream();
           String parseRequest = readString(inputStream);
           System.out.println(parseRequest);
           LoginResponse response = gson.fromJson(parseRequest, LoginResponse.class);

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.