簡體   English   中英

改造在 API 中沒有任何問題地工作:java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

[英]Retrofit didn't work without any problem in API: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

我嘗試使用 Retrofit 並遇到了問題。 錯誤說“你的 JSON 很糟糕,因為它甚至沒有 { ”,但最重要的是 API 工作正常。

服務器響應可以有兩種類型:

{
   status: "error",
   id: "",
   key: "",
   error: "wrong token"
}

並且

{
   status: "ok",
   id: "1",
   key: "1234567abc",
   error: ""
}

所以我不知道為什么會出現這個問題。

日志貓:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:37)
W/System.err:     at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:25)
W/System.err:     at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
W/System.err:     at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
W/System.err:     at okhttp3.RealCall$AsyncCall.run(RealCall.kt:138)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W/System.err:     at java.lang.Thread.run(Thread.java:818)
W/System.err: Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
W/System.err:     at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
W/System.err:     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
W/System.err:   ... 8 more

主要活動:

TextView user;
TextView pass;
Button login;

@Override
public void onCreate(Bundle savedInstanceState) {
        Mint.initAndStartSession(this.getApplication(), "123456");
        setContentView(R.layout.activity_login);
        super.onCreate(savedInstanceState);

        user = (TextView)findViewById(R.id.username);
        pass = (TextView)findViewById(R.id.password);
        login = (Button)findViewById(R.id.btn_login);
}

public void onClickLogin(View view) {
        login.setEnabled(false);

        NetworkService.getInstance()
                .getUserApi()
                .getTokenSession(user.getText().toString(), pass.getText().toString())
                .enqueue(new Callback<Session>() {
                    @Override
                    public void onResponse(Call<Session> call, Response<Session> response) {
                        Session session = response.body();

                        if(session.getStatus() == "ok")
                        {
                            // do usefull work
                        } else {
                            showLoginFailed(R.string.invalid_username_password);
                        }
                    }

                    @Override
                    public void onFailure(Call<Session> call, Throwable t) {
                        showLoginFailed(R.string.bad_network);
                        t.printStackTrace();
                    }
                });
        login.setEnabled(true);
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }

Singleton,其中有API。

public class NetworkService {
    private static NetworkService mInstance;
    private static final String BASE_URL = "https://example.com/api/";
    private Retrofit mRetrofit;

    private NetworkService() {
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        OkHttpClient.Builder client = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        client.addInterceptor(interceptor);

        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client.build())
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }

    public static NetworkService getInstance() {
        if (mInstance == null) {
            mInstance = new NetworkService();
        }
        return mInstance;
    }

    public UserApi getUserApi() {
        return mRetrofit.create(UserApi.class);
    }
}

應用程序接口:

public interface UserApi {
    @GET("users/user.php")
    public Call<Session> getTokenSession(@Query("login") String login, @Query("password") String pass);
}

POJO 對象:

public class Session {
    @SerializedName("status")
    private String status = null;
    @SerializedName("error")
    private String error = null;
    @SerializedName("id")
    private Integer idPerson = null;
    @SerializedName("key")
    private String token = null;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }

    public int getIdPerson() {
        return idPerson;
    }

    public void setIdPerson(int idPerson) {
        this.idPerson = idPerson;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }
}

JSON 無效,您的代碼沒有問題。

添加引號... ;)

{
  "status": "error",
  "id": "",
  "key": "",
  "error": "wrong token"
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM