【问题标题】:Why does my Gson object keep returning null?为什么我的 Gson 对象一直返回 null?
【发布时间】:2020-04-20 17:22:16
【问题描述】:

我正在尝试将 JSON 数据解析为一个类,但 gson.fromJson(response, bitt::class.java) 一直返回 null。

class bitt(@SerializedName("result")val result: String) {
  val someVal: String = "string"
  fun method() {
    print("something")
  }
}

val response: String = "{'success':true,'message':'','result':'Im a sult'}"
println(response)
val gson = Gson()
val ticker = gson.fromJson(response, bitt::class.java)
println(ticker)

我在这里做错了什么?

【问题讨论】:

    标签: json kotlin gson


    【解决方案1】:

    JSON 总是使用双引号 ",而不是单引号 '。您的 response 使用单引号,因此它不是有效的 JSON。

    与许多其他语言一样,您可以使用\" 在字符串文字中添加双引号:

    val response: String = "{\"success\":true,\"message\":\"\",\"result\":\"I'm a result\"}"
    

    【讨论】:

    • 不幸的是,这对我不起作用。 Ticker 始终为空
    【解决方案2】:

    更改为数据类而不是类

    您的代码示例:

    data class bitt(val result: String = "") {
        val someVal: String = "string"
        fun method() {
            print("something")
        }
    }
    

    【讨论】:

    • 不幸的是它并没有改变任何东西。 Ticker 始终为空
    【解决方案3】:

    我想你需要很长时间才能得到结果 所以股票仍然保持为空

    您可以使用 kotlin 协程来处理它。 或者简单地使用这样的回调

    data class bitt(val result: String = "") {
        val someVal: String = "string"
        fun method() {
            print("something")
        }
    }
    
    fun getTicker(response: String, onComplete: (bitt) -> Unit) {
        val ticker = Gson().fromJson(response, bitt::class.java)
        onComplete(ticker)
    }
    
    val response: String = "{'success':true,'message':'','result':'Im a sult'}"
    println(response)
    getTicker(response){ println(it) }
    

    【讨论】:

    • 很遗憾,但没有。 Ticker 仍然为空。我尝试了您的方法并收到错误消息:java.lang.IllegalStateException:ticker must not be null
    【解决方案4】:

    那么你可能需要使用协程

    https://github.com/Kotlin/kotlinx.coroutines

    data class bitt(val result: String = "") {
        val someVal: String = "string"
        fun method() {
            print("something")
        }
    }
    
    suspend fun getTicker(response: String) = Gson().fromJson(response, bitt::class.java)
    
    fun yourMethod() {
        val response: String = "{'success':true,'message':'','result':'Im a sult'}"
        println(response)
        CoroutineScope(IO).launch {
            val ticker = getTicker(response)
            println(ticker)
        }
    
    }
    

    KotlinConf 2017 - Introduction to Coroutines by Roman Elizarov

    【讨论】:

    • 感谢您的所有帮助,不幸的是我无法解决这个问题,我不知道是什么原因造成的。我写了一个函数,我将一个 json 传递给它,然后我手动解析它。
    猜你喜欢
    • 2019-01-19
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-25
    • 2011-09-27
    相关资源
    最近更新 更多