【问题标题】:Moshi with Retrofit send empty request带改造的 Moshi 发送空请求
【发布时间】:2021-12-13 09:37:35
【问题描述】:

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

【问题讨论】:

    标签: java android kotlin retrofit mosh


    【解决方案1】:

    只需将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了解更多信息。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    我的解决方案

    工厂

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

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-08-05
    • 2018-11-13
    • 2020-01-21
    • 2020-06-04
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    相关资源
    最近更新 更多