Moshi with Retrofit 发送空请求

Moshi with Retrofit send empty request

我的应用程序每次都会发送我的位置。当我禁用地理定位时。我想发送 {"latitude":null,"longitude":null} 但是发送 {}

型号

@Serializable
data class PointBody(
    @Json(name = "latitude") val latitude: Double?,
    @Json(name = "longitude") val longitude: Double?
)

请求

 @POST(Path.LOCATION)
    suspend fun sendPoint(
        @Body point: PointBody
    )

改造

private fun provideRetrofit(moshi: Moshi, client: OkHttpClient) = Retrofit.Builder()
    .client(client)
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .baseUrl("Base")
    .build()

莫氏

private fun provideMoshi(): Moshi {
    return Moshi
        .Builder()
        .add(KotlinJsonAdapterFactory())
        .build()
}

我的解决方案

工厂

@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class SerializeNulls

class SerializeNullsFactory : JsonAdapter.Factory {
    override fun create(type: Type, annotations: Set<Annotation?>, moshi: Moshi): JsonAdapter<*>? {
        val nextAnnotations = Types.nextAnnotations(
            annotations,
            SerializeNulls::class.java
        ) ?: return null
        return moshi.nextAdapter<Any>(this, type, nextAnnotations).serializeNulls()
    }
}

型号

@Serializable
data class PointBody(
    @SerializeNulls val latitude: Double?,
    @SerializeNulls val longitude: Double?
)

莫氏

private fun provideMoshi(): Moshi {
    return Moshi
        .Builder()
        .add(SerializeNullsFactory())
        .add(KotlinJsonAdapterFactory())
        .build()
}

您只需将 withNullSerialization() 函数添加到 MoshiConverterFactory 即可解决。

    @Singleton
    @Provides
    fun provideMoshi(): Moshi =
        Moshi.Builder()
            .add(KotlinJsonAdapterFactory())
            .build()
    
    @Singleton
    @Provides
    fun provideMoshiConverterFactory(moshi: Moshi): MoshiConverterFactory =
        MoshiConverterFactory.create(moshi).withNullSerialization()

代码来自 MoshiConverterFactory.java

...
  /** Return a new factory which includes null values into the serialized JSON. */
  public MoshiConverterFactory withNullSerialization() {
    return new MoshiConverterFactory(moshi, lenient, failOnUnknown, true);
  }
...

请检查 MoshiConverterFactory.java 了解更多信息。