我需要从三明治类获得breadType属性。我有两个类,它们都是可序列化的:
@Serializable
class MyFood {
var name: String? = null
var price: Int? = null
var sand: Sandwich? = null
}
@Serializable
class Sandwich{
var breadType: String? = null
}这个JSON:
"MyFood": {
"name": "Sandwich double",
"price": 100.00,
"breadType": 100.00
}我得到了JsonUnknownKeyException异常:
"Strict JSON encountered unknown key: breadType\nYou can disable strict mode to skip unknown keys"我做错什么了!?
发布于 2020-05-12 19:26:22
如果您使用的是Retrofit:
在改造转炉厂使用JsonConfiguration(strictMode = false)。
// your retrofit builder
.addConverterFactory(
Json(
JsonConfiguration(strictMode = false)
).asConverterFactory(MediaType.get("application/json"))
)换句话说,您应该使用Json.nonstrict.parse()而不是Json.parse()。
或者我们可以传递构造函数:
serializer = KotlinxSerializer(Json.nonstrict)编辑:
根据您的json,您的课程应该是这样的:
Serializable
class MyFood {
var name: String? = null
var price: Int? = null
var breadType: double? = null
}这是可行的,但是如果您想使用三明治类,那么您的json应该如下所示:
"MyFood": {
"name": "Sandwich double",
"price": 100.00,
"sand": {
"breadType":100.00
}
}https://stackoverflow.com/questions/61760143
复制相似问题