Moshi/Kotlin - How to serialize NULL JSON strings into empty strings instead?

怎甘沉沦 提交于 2020-01-01 05:29:10

问题


I'm trying to write a null-safe String adapter that will serialize this JSON {"nullString": null} into this: Model(nullString = "") so that any JSON with a 'null' value that I expect to be a String will be replaced with "" (assuming there exists a data class like this: data class Model(val nullString: String))

I wrote a custom adapter to try and handle this:

class NullStringAdapter: JsonAdapter<String>() {
    @FromJson
    override fun fromJson(reader: JsonReader?): String {
        if (reader == null) {
            return ""
        }

        return if (reader.peek() == NULL) "" else reader.nextString()
    }

    @ToJson
    override fun toJson(writer: JsonWriter?, value: String?) {
        writer?.value(value)
    }
}

...in an attempt to solve this parsing error:

com.squareup.moshi.JsonDataException: Expected a name but was NULL at path $.nullString

Moshi parsing code:

val json = "{\"nullString\": null}"

val moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .add(NullStringAdapter())
    .build()

val result = moshi.adapter(Model::class.java).fromJson(configStr)

What am I missing here? Still new to moshi so any help is appreciated!


回答1:


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<Unit>()
    return ""
  }
}

and use add the adapter:

val moshi = Moshi.Builder()
    .add(NULL_TO_EMPTY_STRING_ADAPTER)
    .add(KotlinJsonAdapterFactory())
    .build()


来源:https://stackoverflow.com/questions/46607828/moshi-kotlin-how-to-serialize-null-json-strings-into-empty-strings-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!