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

前端 未结 1 1606
自闭症患者
自闭症患者 2021-02-08 19:38

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

1条回答
  •  盖世英雄少女心
    2021-02-08 19:55

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

    0 讨论(0)
提交回复
热议问题