我正在使用 kotlinx.serialization结合 retrofit .我收到的 json 响应将根据它包含的属性而有所不同。在大多数情况下,我的应用程序中的数据模型包含的字段比我在响应中收到的要多。我无法控制它,所以我需要在代码中处理它。
Kotlinx.serialization 抛出 MissingFieldException
在这种情况下。我知道在使用 Json.parse
时您可以将其包装在 try-catch block 中并忽略此类错误。但由于我使用的是改造,我看不到使用这种方法的方法:
网络服务.kt
interface WebService {
@GET("person.json")
fun getPerson(): Call<MainActivity.Person>
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
@Serializable
data class Person(val name: String, val species: String, val missing: String)
@UnstableDefault
override fun onCreate(savedInstanceState: Bundle?) {
val mediaType = "application/json".toMediaTypeOrNull()
mediaType?.let {
retrofit = Retrofit.Builder()
.addConverterFactory(Json.nonstrict.asConverterFactory(it))
.baseUrl(baseUrl)
.build()
}
webService = retrofit.create(WebService::class.java)
GlobalScope.launch {
val person = fetchPerson(webService)
}
}
private suspend fun fetchPerson(webService: WebService): Person {
return suspendCancellableCoroutine { cont ->
webService.getPerson()
.enqueue(object : Callback<Person> {
override fun onFailure(call: Call<Person>, t: Throwable) {
Log.e(t.toString(), "Unable to get api response")
cont.cancel(t)
}
override fun onResponse(
call: Call<Person>,
response: Response<Person>
) {
if (response.isSuccessful) {
response.body()?.let { cont.resume(it) }
} else {
cont.cancel(IOException("${response.code()}: ${response.errorBody()}"))
}
}
})
}
}
}
json 响应(在这个组成的示例中)故意省略了“缺失”字段:
{"name":"me", "species":"superhuman"}
由于该 json 不包含
missing
来自数据类的字段,应用程序崩溃并抛出 MissingFieldException
.我想知道如何在改造案例中避免这个问题。谢谢你的帮助。
最佳答案
实际上它无法创建Person
来自 json 的对象作为您的 Person
类构造函数需要 3 个值。您必须满足此要求才能创建对象。
解决此问题的一种可能解决方案是使用 中的默认值。 Kotlin 像这样:
data class Person(
var name: String="",
var species: String="",
var missing: String="")
另一种解决方案是使用具有不同参数的多个构造函数,但是由于您提到它可能会随着时间的推移而有所不同,因此该解决方案可能并不方便。谢谢
关于android - 使用 Retrofit 处理 Kotlin 序列化 MissingFieldException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58333349/