Home > Software design >  GSON error: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $. Why am I getting this er
GSON error: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $. Why am I getting this er

Time:08-28

I created a token based login function using retrofit, however I'm getting this error:

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

I already added Accept header in my interface:

interface MyApi
{
  @Headers("Accept:application/json")
  @POST(Constants.LOGIN_URL)
  fun login(@Body request : LoginRequest) : Call<LoginResponse>
}

I also set lenient as true in my GSON builder:

class ApiClient
{
  private lateinit var apiService : MyApi

  private val gson = GsonBuilder()
    .setLenient()
    .create()

  fun getApiService(context : Context): MyApi {
    if (!::apiService.isInitialized) {
        val retrofit = Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .client(okhttpClient(context))
            .build()

        apiService = retrofit.create(MyApi::class.java)
    }
    return apiService
}

   private fun okhttpClient(context : Context) : OkHttpClient {
    return OkHttpClient.Builder()
        .addInterceptor(AuthInterceptor(context))
        .build()
   }

}

My data class looks like this:

data class LoginRequest(
    @SerializedName("email") var email : String ,
    @SerializedName("password") var password : String ,
    @SerializedName("device_name") var device_name : String = "android")

data class LoginResponse(
    @SerializedName("status_code") var status_code : Int ,
    @SerializedName("auth_Token") var authToken : String ,
    @SerializedName("user") var user : User)

data class User(
    @SerializedName("id") var id : String ,
    @SerializedName("username") var username : String ,
    @SerializedName("first_name") var firstName : String ,
    @SerializedName("last_name") var lastName : String ,
    @SerializedName("email") var email : String)

Can someone help me in this problem?

Tried doing it in postman and this is the response:

If credentials is incorrect:

{
"message": "The provided credentials are incorrect.",
"errors": {
    "email": [
        "The provided credentials are incorrect."
    ]
}
}

If correct:

118|uv9iD1wJHpchg49kmOM1ZvNkg5PPuMeZ4QNl5N0r

CodePudding user response:

response is not correctly formated in JSON format. please debug response from server and validate it

json object start like {"data":"value"}, but the response you are receiving is not like valid JSON, it is simple string...

CodePudding user response:

The problem is you try to call JSON object with the LoginResponse data class but the response is just a string, not a JSON. You can change your function on Api Interface like this

fun login(@Body request : LoginRequest) : Call<String>
  • Related