繁体   English   中英

如何使用改造和 kotlin 进行序列化

[英]How to serialize with retrofit and kotlin

我正在尝试使用 Retrofit 和 Kotlin 将响应序列化到 Session 类,但我有一个错误。 我在这里使用继承,也许这就是我不知道的问题:“java.lang.IllegalArgumentException: Unable to create call adapter for retrofit2.Response<com.mobile.myapplication.Session>”

    open class BaseUser {
        var id:Int=0
        var correo:String=""
        var nombre:String=""
        var apellido:String=""
        var direccion:String=""
        var telefono:String=""
        var imagen:String=""
    }
    class Permiso {
        var id:Int=0
        var aplicacionId:Int=0
        var aplicacionName:String=""
        var lectura:Boolean=false
        var escritura:Boolean=false
    }
    class Session: BaseUser() {
    
        var token:String=""
    
        var permiso:List<Permiso> = emptyList()
    }



class LocalViewModel(private val retro:Retro= Retro()):ViewModel(){
    private val _result = MutableStateFlow("")
    val result:StateFlow<String> = _result

  init {
      viewModelScope.launch {
          val jsonObject= JSONObject()
          jsonObject.put("correo", "xxxxxx.com")
          jsonObject.put("password", "xxxxx")
          Log.d("payload",jsonObject.toString())
          retro.token(jsonObject.toString())
      }
  }


}
@Composable
fun main(vm: LocalViewModel= viewModel()){
    Text(text = "Hello world")
}

interface APIService {
    @POST("api/Auth/SignIn")
    fun requestToken(@Body requestBody: RequestBody): Response<Session>

}

class Retro{
     fun getinstance(): APIService? {
         var service:APIService?=null
        try {
            // Create Retrofit
            val retrofit = Retrofit.Builder()
                .baseUrl("xxxxxxxxx")
                .addConverterFactory(GsonConverterFactory.create())
                .build()

            // Create Service
            service = retrofit.create(APIService::class.java)

        }catch (err:Error){
            Log.e("RETROFIT_ERROR", err.toString())
        }

         return  service
    }

    fun token(payload:String){
        val instance=getinstance()
        val requestBody = payload.toRequestBody("application/json".toMediaTypeOrNull())
        val response = instance?.requestToken(requestBody)
        Log.d("response",response.toString())
    }
}

API 响应是这样的:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJOb21icmUiOiJSaWNoYXJkIiwiQXBlbGxpZG8iOiJWw61xdWV6IiwiQ29ycmVvIjoiUnZpcXVlekBzb2Zub21pYy5jb20iLCJEaXJlY2Npb24iOiJIZXJlZGlhIiwiVGVsZWZvbm8iOiJQw6lyZXoiLCJuYmYiOjE2NTc3MjQzOTksImV4cCI6MTY1Nzc0OTU5OSwiaXNzIjoiaHR0cHM6Ly9zb2Zub21pY2FwaS5henVyZXdlYnNpdGVzLm5ldC8ifQ.HtBEe1XlqyU0YBVyGJ1fs-EUiJn8vbWKqvNci2tOboU",
  "id": 26,
  "correo": "xxxxx.com",
  "nombre": "xx",
  "apellido": "xx",
  "direccion": "xxx",
  "telefono": "xx",
  "imagen": null,
  "permiso": []
}

问题是什么 ???

我不知道为什么,但是使用 Response 不能仅使用 Call 而不是 Response!:

interface APIService {
    @POST("api/Auth/SignIn")
    fun requestToken(@Body requestBody: RequestBody): Call<Session>

}
fun token(payload:String):Session?{
    val instance=getinstance()
    val requestBody = payload.toRequestBody("application/json".toMediaTypeOrNull())
    var session: Session?=null
    val response = instance?.requestToken(requestBody) ?: return null

    response.enqueue(object : Callback<Session?> {
        override  fun onResponse(call: Call<Session?>?, response: Response<Session?>) {
            val statusCode = response.code()
            if (statusCode!=200){
                return
            }
            session = response.body()
        }
        override fun onFailure(call: Call<Session?>?, t: Throwable?) {
            return
        }
    })

    return  session
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM