dor506
dor506

Reputation: 5414

Kotlin - force failing deserialization from json to class, when a non null property not exits in the json?

Assuming we have this class:

  class Test(@SerializedName("Nullablefield")
             val nullable: Int?,
             @SerializedName("NonNullableField")
             val nonNullable: Int)

And we recive this json:

{
    "Nullablefield": 3
}

As you can see, NonNullableField is missing in the json,

When using Gson().fromJson method the property becomes null (even though the property is defined as non null one)

I read about gson using unsafe approach while doing this.

Is there a way to make the deserialization process fail in this case, with Gson or any other library?

I do not want to solve it by assigning a default value to the field.

Upvotes: 1

Views: 319

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8442

You can use Moshi library for parsing json

import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi

fun main() {
    val json = """
{
    "Nullablefield": 3
}        
    """.trimIndent()
    val moshi = Moshi.Builder().build()
    val adapter = moshi.adapter(Test::class.java)
    val test = adapter.fromJson(json)//will crash
    println(test)
}

@JsonClass(generateAdapter = true)
data class Test(
    @Json(name = "Nullablefield")
    val nullable: Int?,
    @Json(name = "NonNullableField")
    val nonNullable: Int
)

Upvotes: 2

Related Questions