0

我的应用每次都会发送我的位置。当我禁用地理定位时。我想发送 {"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()
}
4

2 回答 2

0

我的解决方案

工厂

@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()
}
于 2021-10-29T07:33:57.017 回答
0

您可以解决仅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以获取更多信息。

于 2021-11-09T07:33:14.670 回答