Moshi 将值反序列化为 null

Spe*_*ake 5 android oauth-2.0 moshi retrofit2

我最近从 Gson 切换到 Moshi,但在解析一些 Json 时遇到问题。

{
  "access_token": "-LNe2LQ7DQH5Y2zs_W5iUumKuaUE",
  "token_type": "bearer",
  "device_id": "461f-837e-af5050c92fe9",
  "expires_in": 3600,
  "scope": "*"
}
Run Code Online (Sandbox Code Playgroud)

这是模型类:

data class AuthToken(
        @Json(name = "access_token") val accessToken: String,
        @Json(name = "token_type") val tokenType: String,
        @Json(name = "device_id") val deviceId: String,
        @Json(name = "expires_in") val expiresIn: Int,
        @Json(name = "scope") val scope: String
)
Run Code Online (Sandbox Code Playgroud)

每当我在改造客户端中切换到使用 Moshi 时,都会收到以下错误:

java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull
Run Code Online (Sandbox Code Playgroud)

我已将该字段设置为可为空,但它始终反序列化为空。我检查了我的改造响应,使用 Gson 或 Moshi 时(显然)是相同的。我究竟做错了什么?

Spe*_*ake 4

由于某种原因,当我明确告诉AuthToken类生成适配器时 - 我没有收到空值。

@JsonClass(generateAdapter = true)
data class AuthToken(
        @Json(name = "access_token") val accessToken: String,
        @Json(name = "token_type") val tokenType: String,
        @Json(name = "device_id") val deviceId: String,
        @Json(name = "expires_in") val expiresIn: Int,
        @Json(name = "scope") val scope: String
)
Run Code Online (Sandbox Code Playgroud)

  • 如果您不使用 Moshi 的 Kotlin 支持(反射 KotlinJsonAdapterFactory 或 codegen 适配器),则无法正确读取 `@Json` 名称。(它们不会添加到字段中,并且默认的反射 Java 适配器看不到它们。) (2认同)