Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Moshi applies the default value of kotlin to the null field of json

Json

{
    "id": "1",
    "name": "name",
    "email": null
}

User

data class User(
    var id: Int = 0,
    var name: String = "",
    var email: String = ""
)

I want to apply default value for null value when parsing json. (Apply the above email field as a non-null ""(blank))

like image 786
dylan.kwon Avatar asked Apr 08 '19 05:04

dylan.kwon


2 Answers

Details: https://code.luasoftware.com/tutorials/android/android-moshi-adapter-convert-null-to-empty-string/

TL;DR;

Create NullToEmptyStringAdapter.

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class NullToEmptyString

class NullToEmptyStringAdapter {
    @ToJson
    fun toJson(@NullToEmptyString value: String?): String? {
        return value
    }

    @FromJson
    @NullToEmptyString
    fun fromJson(@javax.annotation.Nullable data: String?): String? {
        return data ?: ""
    }
}

Apply NullToEmptyStringAdapter to your data class.

data class User(
    var id: Int = 0,
    var name: String = "",
    @NullToEmptyString
    var email: String = ""
)

Setup Moshi

val moshi = Moshi.Builder()
    .add(NullToEmptyStringAdapter())
    .add(KotlinJsonAdapterFactory())
    .build()
like image 135
Stanley Ko Avatar answered Sep 22 '22 01:09

Stanley Ko


I found this question when I was finding a solution to this question but I do not want to use an adapter because you can only default to one value and one type. It is not flexible for me.

Instead of add an adapter, I use getter and setter in Kotlin.

data class User(
    @Json(name = "id") var _id: Int?,
    @Json(name = "name") var _name: String?,
    @Json(name = "email") var _email: String?
) {
    var id: Int
        get() = _id ?: 0
        set(value) {
            _id = value
        }

    var name: String
        get() = _name ?: ""
        set(value) {
            _name = value
        }

    var email: String
        get() = _email ?: ""
        set(value) {
            _email = value
        }
}

Using this method, you are give different default values if you want.

like image 37
Joshua Avatar answered Sep 21 '22 01:09

Joshua