I\'m trying to write a null-safe String adapter that will serialize this JSON {\"nullString\": null}
into this: Model(nullString = \"\")
so that any JS
The immediate problem is the missing reader.nextNull()
call to consume the null value.
There are a couple other cleanup things you can do here, too.
With @FromJson
, implementing JsonAdapter
is unnecessary.
Also, the JsonReader and JsonWriter are not nullable.
object NULL_TO_EMPTY_STRING_ADAPTER {
@FromJson fun fromJson(reader: JsonReader): String {
if (reader.peek() != JsonReader.Token.NULL) {
return reader.nextString()
}
reader.nextNull()
return ""
}
}
and use add the adapter:
val moshi = Moshi.Builder()
.add(NULL_TO_EMPTY_STRING_ADAPTER)
.add(KotlinJsonAdapterFactory())
.build()