The following adapter convert reading of json string such as {"name":null}
to name = ""
.
Create a NullToEmptyString
adapter class. I am using a @JsonQualifier
as I don't want to apply this adapter to all String
.
@Retention(AnnotationRetention.RUNTIME)@JsonQualifierannotation class NullToEmptyStringclass NullToEmptyStringAdapter { @ToJson fun toJson(@NullToEmptyString value: String?): String? { return value } @FromJson @NullToEmptyString fun fromJson(@Nullable data: String?): String? { return data ?: "" }}
Apply NullToEmptyStringAdapter
.
data class PhotoPin ( @Json(name = "name") @NullToEmptyString var name: String = "" )
Setup Moshi
val moshi = Moshi.Builder() .add(NullToEmptyStringAdapter()) .add(KotlinJsonAdapterFactory()) .build()
NOTE: KotlinJsonAdapterFactory
is required (for Kotlin
) else the behaviour differ.
Test Code
@RunWith(AndroidJUnit4::class)class MoshiTest { lateinit var moshi: Moshi lateinit var adapter: JsonAdapter<PhotoPin> @Before fun init() { moshi = Moshi.Builder() .add(NullToEmptyStringAdapter()) .add(KotlinJsonAdapterFactory()) .build() adapter = moshi.adapter<PhotoPin>(PhotoPin::class.java) } @Test fun testNameNull() { var item = adapter.fromJson("""{"name":null}""")!! assertThat(item.name, Is("")) }}
References: