【问题标题】:Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $ Android Refrofit预期为 BEGIN_OBJECT,但在第 1 行第 1 列路径为 STRING $ Android Retrofit
【发布时间】:2020-09-22 10:17:39
【问题描述】:

我正在尝试发布用户名、密码并从 Android 中的 JSON 获取结果。但是在我点击登录按钮后,我收到了这个错误。

进程:com.tolgahantutar.bexworkfloww,PID:12957 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 预期 BEGIN_OBJECT 但在第 1 行第 1 列路径 $

授权会话模型;

package com.tolgahantutar.bexworkfloww.data.models

import com.google.gson.annotations.SerializedName


data class AuthorizeSessionModel(
    @SerializedName("UserID")
    var UserID: Int,
    @SerializedName("DatePasswordChanged")
    var DatePasswordChanged: String,
    @SerializedName("ForceToChangePassword")
    var ForceToChangePassword: String,
    @SerializedName("LoginType")
    var LoginType: String,
    @SerializedName("UserName")
    var UserName: String,
    @SerializedName("IsActive")
    var IsActive: Boolean,
    @SerializedName("UserFirstName")
    var UserFirstName: String,
    @SerializedName("UserLastName")
    var UserLastName: String,
    @SerializedName("ID")
    var ID: Int
)

授权会话响应;

package com.tolgahantutar.bexworkfloww.data.network

import com.google.gson.annotations.SerializedName
import com.tolgahantutar.bexworkfloww.data.models.AuthorizeSessionModel

data class AuthorizeSessionResponse (
    @SerializedName("Value")
    val authorizeSessionModel: AuthorizeSessionModel ,
    @SerializedName("Result")
    val Result : Boolean,
    @SerializedName("Description")
    val Description: String,
    @SerializedName("Code")
    val Code: String
)

我的 API ;

package com.tolgahantutar.bexworkfloww.data.network

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST

interface VisaServicesApi {
@FormUrlEncoded
@POST("index#!/Visa32Services/Session_AuthorizeSession")

suspend fun userLogin(
    @Field("SessionID") SessionID:Int,
    @Field("AuthorityID") AuthorityID: Int,
    @Field("UserName") UserName: String,
    @Field("Password") Password: String,
    @Field("LoginType") LoginType: String
):Response<AuthorizeSessionResponse>

companion object{
operator fun invoke():VisaServicesApi{
    val logging = HttpLoggingInterceptor()
    logging.setLevel(HttpLoggingInterceptor.Level.BODY)
    val okHttpClient = OkHttpClient.Builder().addInterceptor(logging).build()
    val gson = GsonBuilder()
        .setLenient()
        .create()
return Retrofit.Builder()
    .client(okHttpClient)
    .baseUrl("http://bexfatestv2service.saasteknoloji.com/swagger/ui/")
    .addConverterFactory(GsonConverterFactory.create(gson))
    .build()
    .create(VisaServicesApi::class.java)

}
}
}

授权会话存储库;

package com.tolgahantutar.bexworkfloww.data.network.repositories

import com.tolgahantutar.bexworkfloww.data.network.AuthorizeSessionResponse
import com.tolgahantutar.bexworkfloww.data.network.SafeApiRequest
import com.tolgahantutar.bexworkfloww.data.network.VisaServicesApi

class AuthorizeSessionRepository(
    private val api : VisaServicesApi
):SafeApiRequest(){

suspend fun userLogin(SessionID: Int,AuthorityID: Int,UserName: String,Password : String,LoginType: String):AuthorizeSessionResponse{
return apiRequest { api.userLogin(SessionID, AuthorityID, UserName, Password, LoginType) }

}


}

AuthViewModel;

package com.tolgahantutar.bexworkfloww.ui.auth

import androidx.lifecycle.ViewModel
import com.tolgahantutar.bexworkfloww.data.network.repositories.AuthorizeSessionRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class AuthViewModel (
    private val repository: AuthorizeSessionRepository
):ViewModel(){

suspend fun userLogin(
SessionID : Int,
AuthorityID: Int,
UserName: String,
Password : String,
LoginType: String
)= withContext(Dispatchers.IO){repository.userLogin(SessionID, AuthorityID, UserName, Password, LoginType)}
}

登录活动;

package com.tolgahantutar.bexworkfloww.ui.auth

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.tolgahantutar.bexworkfloww.R
import com.tolgahantutar.bexworkfloww.databinding.ActivityLoginBinding
import com.tolgahantutar.bexworkfloww.util.ApiException
import com.tolgahantutar.bexworkfloww.util.NoInternetException
import kotlinx.coroutines.launch
import org.kodein.di.KodeinAware
import org.kodein.di.android.kodein
import org.kodein.di.generic.instance

class LoginActivity : AppCompatActivity(), KodeinAware {

    override val kodein by kodein()
    private val factory : AuthViewModelFactory by instance<AuthViewModelFactory>()
    private lateinit var binding : ActivityLoginBinding
    private lateinit var viewModel:AuthViewModel




    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


binding = DataBindingUtil.setContentView(this,R.layout.activity_login)
        viewModel = ViewModelProvider(this,factory).get(AuthViewModel::class.java)

binding.buttonLogin.setOnClickListener{
loginUser()
}
    }
private fun loginUser(){

    val SessionID = 0
    val AuthorityID = 0
    val userName =binding.editTextUsername.text.toString().trim()
    val password = binding.editTextPassword.text.toString().trim()
    val LoginType = "System"

    lifecycleScope.launch {
        try{
val authResponse = viewModel.userLogin(SessionID,AuthorityID,userName,password,LoginType)

            if(authResponse.Result){
                Toast.makeText(applicationContext, "Login Successfull!", Toast.LENGTH_LONG).show()
            }else{
                Toast.makeText(applicationContext, "Login Failed!!", Toast.LENGTH_LONG).show()
            }
        }catch (e: ApiException){
            e.printStackTrace()
        }catch (e: NoInternetException){
            e.printStackTrace()
        }
    }


}
}

这里是我的 Json 响应;

{
  "Value": {
    "UserID": 0,
    "DatePasswordChanged": "2020-09-22T07:26:33.654Z",
    "ForceToChangePassword": 0,
    "LoginType": "string",
    "UserName": "string",
    "IsActive": true,
    "UserFirstName": "string",
    "UserLastName": "string",
    "ID": 0
  },
  "Result": true,
  "Description": "string",
  "Code": "string"
}

【问题讨论】:

  • 您是否在日志中得到了想要的响应。您可以通过过滤日志中的 http 一词来检查。
  • 没有。我没有收到来自 URL 的任何响应
  • 您能再次检查您的 JSON,您确定这是正确的架构吗?
  • 当我从 swagger 运行它时,我意识到我的 JSON 是正确的。但是当我使用 POSTMAN 查看响应时,我得到的代码充满了 HTML
  • @TolgahanTutar url 抛出错误而不是成功响应。您应该检查改造代码中的响应代码

标签: android json kotlin retrofit


【解决方案1】:

您可能需要创建一个数据类来包装您的 AuthorizeSessionResponse 类。

类似:

data class AuthorizeSessionResponseWrapper (var authorizeSessionResponse: AuthorizeSessionResponse)

【讨论】:

  • 你能解释一下把这个类放在哪里吗?很抱歉问这个问题,但我是 Android 开发的新手
  • @TolgahanTutar 根据您发布的回复,您不需要这样做
  • @AdityaKurkure 好的,我明白了。但我仍然不知道错误在哪里。我被它困住了
猜你喜欢
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-04-09
  • 1970-01-01
  • 2017-05-12
相关资源
最近更新 更多