kotlin ktor-failing-to-parse-response-no-transformation-found:尝试解析列表< >

9gm1akwq  于 2023-08-06  发布在  Kotlin
关注(0)|答案(1)|浏览(97)

我正在将一个工作应用程序从SWIFT转换到Kotlin以支持Android设备,并且在KTOR反序列化方面遇到了问题。协助是赞赏!
当尝试将JSON响应反序列化为List <>时,会出现以下错误:
异常:io. ktor. client. call. NoTransformationFoundException:未找到转换:class io. ktor. utils. io. ByteBufferChannel-> class com. pollensystems. precisionview. MainActivity $Model
下面是失败的代码-请提供建议!
@Serializable数据类SiteResponse(var SitesID:Int,var SiteName:String,var SitePath:字符串)

private suspend fun loadSites() {
    val text = "Loading Sites..."
    val duration = Toast.LENGTH_SHORT

    val toast = Toast.makeText(this, text, duration) // in Activity
    toast.show()

    val getsitesforcustomerurl = "https://*****************/GetSitesForCustomer/cmd"

    val client = HttpClient() {
        install(ContentNegotiation) {
            json()
        }
    }

    val response: HttpResponse = client.post(getsitesforcustomerurl) {
        contentType(ContentType.Application.Json)
        setBody(Customer(58))
    }

    if (response.status.value in 200..299) {
        Log.d(TAG, "Successful Response")

        Log.d(TAG, response.bodyAsText())

        try {
            val sites: List<SiteResponse> = response.body()

            if (sites == null)
                Log.d(TAG, "Sites is null")
            else
                Log.d(TAG, "Number of sites: " + sites.items.size.toString())
        } catch (e: Exception) {
            Log.d(TAG, "Exception: $e")
        }
    }
}

字符串
}
从response.bodyAsText()收到的响应JSON可以很好地打印到日志中。[{"SitesID ":347,"站点名称":"Avonlea Barley 2022","SitePath":" stoller_avonlea_barley_2022 "},{" SitesID ":345,"站点名称":"Avonlea Canola 2022","SitePath":" stoller_avonlea_canola_2022 "},{"SitesID ":344,"站点名称":"Avonlea Lentils 2022","SitePath":" stoller_avonlea_lentils_2022 "},{" SitesID ":346,"站点名称":"Avonlea Wheat 2022","SitePath":" stoller_avonlea_wheat_2022 "},{"SitesID ":254,"站点名称":"Chula GA Pecans 2021","SitePath":" stoller_chula "},{" SitesID ":354,"站点名称":“Clovis CA Cotton 2022”,“SitePath”:" stoller_clovis_cotton_2022 "}]
我期待JSON成功反序列化为sites val,在本例中,它将sites val的大小打印为6。
我也试过阵法,运气不好。
val sites:Array = response. body()
已确认这不是List <>对象所独有的。我的配置中有些东西似乎不正确。类似的反序列化失败了一个简单的json类:
{"UserID ":50," CustomerID ":94," isAdmin ":true," Guid ":" 658d6b92-fd9a-4290 - 828e-da1c11c9a217 "," Expiry ":" 2023 - 08 - 01T00:12:35 + 00:00 "}
@Serializable data class LoginRequest(val Email:String,val密码:字符串)

@Serializable
data class LoginResponse(
    val UserID: Int,
    val CustomerID: Int,
    val isAdmin: Boolean,
    val Guid: String,
    val Expiry: String
)

fun login(username: String, password: String): Result<LoggedInUser> {
    try {
        Log.d(TAG, "Logging in using userid $username password $password")

        runBlocking {
            val loginurl = "https://********************"

            val client = HttpClient() {
                install(ContentNegotiation) {
                    json()
                }
            }

            val response: HttpResponse = client.post(loginurl) {
                contentType(ContentType.Application.Json)
                setBody(LoginRequest(username, password))
            }

            if (response.status.value in 200..299) {
                Log.d(TAG, "Successful Response")

                Log.d(TAG, response.bodyAsText())

                try {
                    val lr: LoginResponse = response.body()

                    if (lr == null)
                        Log.d(TAG, "Lr is null")
                    else
                        Log.d(TAG, "Successful Login, Token: " + lr.Guid)
                } catch (e: Exception) {
                    Log.d(TAG, "Exception: $e")
                }
            }
        }
    }
}


以下是我的进口清单:

import android.util.Log
import com.pollensystems.precisionview.data.model.LoggedInUser
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.HttpResponse
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import java.io.IOException
import kotlinx.coroutines.runBlocking
import kotlinx.serialization.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.serialization.kotlinx.json.*

lyr7nygr

lyr7nygr1#

这个方法奏效了:

try {

val json = kotlinx.serialization.json.Json {
   ignoreUnknownKeys = true
}
                    
val lr : LoginResponse = json.decodeFromString(response.bodyAsText())

if (lr == null)
     Log.d(TAG, "Lr is null")
else
     Log.d(TAG, "Successful Login, Token: " + lr.Guid)
} catch (e: Exception) {
     Log.d(TAG, "Exception: $e")
}

字符串

相关问题