rav215
rav215

Reputation: 3

Why does my Gson object keep returning null?

I'm trying to parse JSON data to a class but gson.fromJson(response, bitt::class.java) keeps returning 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)

What am I doing wrong here?

Upvotes: 0

Views: 157

Answers (4)

then you might need to use Coroutine

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

Upvotes: 0

I guess it takes long time before you get the result back so the ticker still remain null

you can use kotlin coroutines to handle it. or simply use callback like this

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) }

Upvotes: 0

Nitrodon
Nitrodon

Reputation: 3435

JSON always uses double quotes ", not single quotes '. Your response uses single quotes, so it is not valid JSON.

As in many other languages, you can use \" to put a double quote in a string literal:

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

Upvotes: 1

change to Data Class instead of Class

example from your code:

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

Upvotes: 0

Related Questions