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.

annotation class NullToEmptyString

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

    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()

NOTE: KotlinJsonAdapterFactory is required (for Kotlin) else the behaviour differ.

Test Code

class MoshiTest {
    lateinit var moshi: Moshi
    lateinit var adapter: JsonAdapter<PhotoPin>

    fun init() {
        moshi = Moshi.Builder()
        adapter = moshi.adapter<PhotoPin>(

    fun testNameNull() {
        var item = adapter.fromJson("""{"name":null}""")!!

        assertThat(, Is(""))


This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.