Android Retrofit Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

萝らか妹 提交于 2021-01-26 19:28:16

问题


I am using okhttp Retrofit in my Android App to make network requests. On one of the requests I get this error:

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

I see a 201 response in the logs but Retrofit throws this error. Below is my code.

signup(signupParams, new Callback<Member>() {
            @Override
            public void success(Member member, Response response) {
                if (member != null) {
                    UserAccount userAccount = new UserAccount(member);
                    userAccount.save();
            }

            @Override
            public void failure(RetrofitError re) {
                BusProvider.post(new SignupFailedEvent(re, email));
            }
        });

signupParams value is --

{"emailAddress":"test@gmail.com","password":"tester123","userSource":"APH"}

I have tested this json with jsonLint and it is a valid json. And this is my Member Class which should be the response ideally.

public class Member {
    public String emailAddress;
    public String token;
    public long id;
    public String firstName;
    public String lastName;
}

Example of the response should be something like this:

{
    "emailAddress": "test@gmail.com",
    "id": 1437811,
    "token": "sdhshdghsdhhsdbcjhbsjdhc",
    "firstName": "John",
    "lastName": "Smith"
}

回答1:


If the source code that you posted for the Member class is accurate, then you are not getting the response JSON that you think you are.

The error message means that the JSON parser found a String where it expected a complex object.

Since you don't have any complex objects in the Member class, the result probably just isn't valid JSON (it doesn't start with an opening curly bracket).

Try either turning on verbose logging in Retrofit as suggested in one of the comments, or posting the same data to the API using a tool like "Postman", and see what the result actually is.




回答2:


This is cause .your respons is not json formated . it may include with string or expected } . to identify this .you have to check with postman and change view type in body as HTML . there you can see full response and you can validate with *https://jsonlint.com/ . else in the case of Dynamic json . you can use JsonElement as response.




回答3:


if you sure the postman work, and the model same as the JSON parameter,

maybe you use the "accept-encoding: gzip" or like that in your request header.

retrofit doesn't work with gzip, remove that from the header.



来源:https://stackoverflow.com/questions/32959612/android-retrofit-expected-begin-object-but-was-string-at-line-1-column-1-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!