Android Moshi Adapter Convert Null To Empty String With JsonQualifier (Kotlin)

May 14, 2018

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>(    }    @Test    fun testNameNull() {        var item = adapter.fromJson("""{"name":null}""")!!        assertThat(, Is(""))    }}


❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.