如何用kotlinx.serialization解析服务器返回的裸null响应?
解决方法
方案一:修改Json配置允许顶层Null
你的问题核心是kotlinx序列化默认不允许顶层的Null值(即直接返回null而非对象),只需在Json配置中添加allowTopLevelNulls = true即可:
@OptIn(ExperimentalSerializationApi::class) @Singleton @Provides fun provideJson(): Json = Json { allowTrailingComma = true encodeDefaults = true explicitNulls = false ignoreUnknownKeys = true prettyPrint = true isLenient = true allowTopLevelNulls = true // 新增此配置,允许顶层解析Null }
这个配置会让序列化器接受顶层的JSON Null值,并将其解析为DataDto?类型的null,完美适配后端返回的裸null响应。
方案二:自定义Converter处理特殊响应
如果方案一无效(比如后端返回的其实是字符串"null"而非JSON Null),可以自定义Retrofit的Converter来手动处理这种特殊情况:
- 实现自定义Converter Factory:
class NullStringConverterFactory(private val json: Json) : Converter.Factory() { override fun responseBodyConverter( type: Type, annotations: Array<out Annotation>, retrofit: Retrofit ): Converter<ResponseBody, *>? { // 获取默认的JSON转换器 val delegate = json.asConverterFactory("application/json".toMediaType()) .responseBodyConverter(type, annotations, retrofit) as Converter<ResponseBody, Any?> return Converter { body -> val responseString = body.string().trim() // 如果响应是裸"null"字符串,直接返回null if (responseString == "null") { null } else { // 否则交给默认转换器解析 delegate.convert(ResponseBody.create("application/json".toMediaType(), responseString)) } } } }
- 在Retrofit构建时添加这个自定义Factory(注意要放在JSON转换器之前):
Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(NullStringConverterFactory(provideJson())) // 先处理特殊情况 .addConverterFactory(provideJson().asConverterFactory("application/json".toMediaType())) .build()
这样无论后端返回的是JSON Null还是裸字符串null,都能正确解析为DataDto?的null值。
内容的提问来源于stack exchange,提问作者Mark
相关产品推荐
相关产品推荐

