服务器在moshi中为该值发送null时,kotlin数据类中的默认值不起作用

时间:2018-11-28 09:04:27

标签: android kotlin retrofit2 moshi

我使用Moshi从服务器解析json。如果服务器未设置项目默认值,则发送null!但是服务器不会发送该项目的默认值集。

json:

{"percentChange": null,"change": "-2500.00","value": "130000","name": null}

数据类:

@JsonClass(generateAdapter = true) data class Reference(val name:String? = "-",val value: Double,val change: Double,val percentChange: Double? = -10.0,)

,但name和percentChange的数据为null,对于name应该为“-”,对于percentChange应该为“ -10.0”。如果服务器未发送名称和percentChange,则默认值有效,但如果发送该空默认值,则无效!

我使用converter-moshi:2.4.0和翻新版:2.4.0

1 个答案:

答案 0 :(得分:1)

之所以按预期工作,是因为在JSON中作为键的值的空文字在语义上与没有键和值的语义不同。

您可以为您的用例创建一个自定义JsonAdapter。

@JsonClass(generateAdapter = true)
data class Reference(
  @Name val name: String = "-",
  val value: Double,
  val change: Double,
  val percentChange: Double? = -10.0
) {
  @Retention(RUNTIME)
  @JsonQualifier
  annotation class Name

  companion object {
    @Name @FromJson fun fromJson(reader: JsonReader, delegate: JsonAdapter<String>): String {
      if (reader.peek() == JsonReader.Token.NULL) {
        reader.nextNull<Unit>()
        return "-"
      }
      return delegate.fromJson(reader)!!
    }

    @ToJson fun toJson(@Name name: String): String {
      return name
    }
  }
}

@Test fun reference() {
  val moshi = Moshi.Builder()
      .add(Reference)
      .build()
  val adapter = moshi.adapter(Reference::class.java)
  val decoded = Reference("-", 130_000.toDouble(), (-2_500).toDouble(), null)
  assertThat(adapter.fromJson(
      """{"percentChange": null,"change": "-2500.00","value": "130000"}"""))
      .isEqualTo(decoded)
  assertThat(adapter.fromJson(
      """{"percentChange": null,"change": "-2500.00","value": "130000","name": null}"""))
      .isEqualTo(decoded)
}