Retrofit在不可为null的字符串(Kotlin)上返回null

问题描述 投票:0回答:1

当我遇到这个问题,我真的不知道这是一个已知的错误还是应该提交错误报告时,我正在用android开发应用程序。这是代码:

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

data class Status(val msg: String, val integer: Int, val msg2:String)

interface API {

  @GET("/json/gson")
  suspend fun gson(): Status
}

val gsonApiCalls = Retrofit.Builder()
  .addConverterFactory(GsonConverterFactory.create())
  .baseUrl("http://localhost:8080")
  .build()
  .create(API::class.java)

suspend fun main(){

  val result = gsonApiCalls.gson()
  println(result)
  result.msg2?.let(::println) ?: println("Null result!")
}

本地服务器代码(Ktor):

import io.ktor.application.*
import io.ktor.response.*
import io.ktor.request.*
import io.ktor.routing.*
import io.ktor.http.*
import io.ktor.gson.*
import io.ktor.features.*

fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)

data class StandardResponse(val msg: String, val integer: Int, val msg2:String?)

@Suppress("unused") // Referenced in application.conf
@kotlin.jvm.JvmOverloads
fun Application.module(testing: Boolean = false) {
    install(ContentNegotiation) {
        gson {
        }
    }

    routing {
        get("/") {
            call.respondText("HELLO WORLD!", contentType = ContentType.Text.Plain)
        }

        get("/json/gson") {
            call.respond(StandardResponse("Hello",34, null))
        }
    }
}

结果是:

Status(msg=Hello, integer=34, msg2=null)
Null result!

[上面的代码是我为测试此行为而制作的示例,但是当我第一次收到NullPointerException时,我意识到这个“错误”在android应用中,我不明白为什么。

该应用程序正在使用远程节点服务器,并且发生了同样的事情。Capture showing the linter thinks this can't be possible

如果这是错误,我应该向Kotlin或Retrofit报告吗?

kotlin nullpointerexception gson retrofit
1个回答
0
投票

我想我已经找到了答案,尽管我认为这是语言所保证的。

Why Kotlin data classes can have nulls in non-nullable fields with Gson?

© www.soinside.com 2019 - 2024. All rights reserved.