【问题标题】:Moshi @Json annotation not working for com.github.kittinunf.fuel.moshi.moshiDeserializerOf?Moshi @Json 注释不适用于 com.github.kittinunf.fuel.moshi.moshiDeserializerOf?
【发布时间】:2019-05-14 07:09:40
【问题描述】:

我有一个响应对象:

data class ResponseObject(
        val notCamelcase: String,
        val param2: String,
        val param3: String
)

请注意响应 JSON 正文中的第一个参数不是驼峰式(如 notCamelCase)。

Furtheron,我触发了 REST 调用with the FUEL library

Fuel.get(someParam)
        .responseObject(moshiDeserializerOf(ResponseObject::class.java)) { _, response, result ->
            try {
                if (response.statusCode == HttpURLConnection.HTTP_OK) {
                    val responseObject = result.component1()
        }

以下是我的导入:

import com.github.kittinunf.fuel.Fuel
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.HttpException
import com.github.kittinunf.fuel.moshi.moshiDeserializerOf

为了在下面的代码中使用驼峰式,我修改了 ResponseObject,如下所示:

data class ResponseObject(
        @Json(name="notCamelcase")
        val notCamelCase: String,
        val param2: String,
        val param3: String
)

因为它is described here....

在这种情况下,notCamelCase 为空。 @Json 是否仅与 com.github.kittinunf.fuel.moshi.moshiDeserializerOf 一起使用?怎么了?

【问题讨论】:

  • 在使用 Kotlin 时请使用反射 KotlinJsonAdapterFactory 或 codegen。下一个版本的 Moshi 将需要它们。

标签: kotlin moshi kotlin-fuel


【解决方案1】:

对 Moshi kotlin 使用 @field:Json() 注释。

data class ResponseObject(
    @field:Json(name="notCamelcase")
    val notCamelCase: String,
    val param2: String,
    val param3: String
)

参考:https://github.com/square/moshi/issues/315 正如讨论中提到的,这仍然是一种解决方法。官方的 Kotlin 支持是正确的方法:https://github.com/square/moshi#kotlin

【讨论】:

  • 这是解决方法。如果您将 Kotlin 与 Moshi 一起使用,请使用官方的 Kotlin 支持。下一个版本的 Moshi 将需要它。
  • 谢谢,@EricCochran。我扩展了当前状态,而不是仅仅链接相关讨论。
猜你喜欢
  • 2020-05-26
  • 1970-01-01
  • 2020-03-21
  • 2021-11-06
  • 2021-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多