{
"id": "1",
"name": "name",
"email": null
}
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))
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With