Home > Software engineering >  Moshi with Retrofit send empty request
Moshi with Retrofit send empty request

Time:10-31

My app send my location every time. when I disable geolocation. i want send {"latitude":null,"longitude":null} but sent {}

Model

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

Request

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

Retorift

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

Moshi

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

CodePudding user response:

My solution

Factory

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

Model

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

Moshi

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