我通过了邮递员的请求,并获得了成功的答复。现在,当我尝试使用Retrofit 2
通过代码执行相同操作时,出现错误:com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
。
最初我收到以下错误:
Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $
,但在将.setLenient()
添加到Gson
builder
之后,就解决了。
我知道,如果Model
与响应不符,通常会发生这种情况。但是这一次我想我已经检查了所有复选框,但是仍然遇到错误。
模型
class LoginResponse(val access_token: String?, val token_type: String?, val user: UserResponse, val expires_at: String)
class UserResponse(
val id: Long?,
val name: String?,
val email: String?,
val created_at: String,
val updated_at: String,
val api_token: String
)
RestApiInterface
@POST(LOGIN)
fun login(@Body user: LoginRequest): Call<LoginResponse>
改造
@Provides
@Reusable
fun provideRetrofit(gson: Gson): Retrofit {
val interceptor = HttpLoggingInterceptor()
interceptor.level =
if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val okBuilder = OkHttpClient.Builder()
okBuilder.addInterceptor(interceptor)
okBuilder.addInterceptor { chain ->
val request = chain.request()
val builder = request.newBuilder()
chain.proceed(builder.build())
}
return Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(API_BASE_URL)
.client(okBuilder.build())
.build()
}
Gson
@Provides
fun providesGson(): Gson {
return GsonBuilder().setLenient().create()
}
回复(邮递员)
{
"access_token": "eyJ0eX...",
"token_type": "Bearer",
"user": {
"id": 1,
"name": "Api",
"email": ".......",
"created_at": "2018-07-09 08:52:31",
"updated_at": "2019-06-12 10:58:36",
"api_token": "OVp5CuRDLQ92tiXobTJNuf4HASfU0xpiMoChVdbyL2OQspajmFDPAqrlCLHD"
},
"expires_at": "2020-06-19 17:30:31"
}