ios - 类型不匹配(Swift.DictionarydebugDescription: "期望解码字典但找到了一个数组。”
问题描述
现在我面临这个错误
'[UserOrderHistory]' 类型的值没有成员 'orderlist'
我的 JSON:
{
"OrderList": [
{
"orderId": 16976,
"userId": 4905,
"pickupdate": "2018-09-23",
},
{
"orderId": 52,
"userId": 4905,
"pickupdate": "2018-08-07",
},
],
"TotalOrder": 2
}
我的可解码模型类:
class UserOrderHistory: Object, Decodable {
var orderlist: [OrderList]?
var TotalO = RealmOptional<Int>()
enum CodingKeys: String, CodingKey {
case orderlist = "OrderList"
case TotalO = "TotalOrder"
}
convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.orderlist = try container.decodeIfPresent(OrderList.self, forKey: .orderlist)
self.TotalO.value = try container.decodeIfPresent(Int.self, forKey: .TotalO)
}
required init() {
super.init()
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
class OrderList: Object, Decodable{
var orderId = RealmOptional<Int>()
var userId = RealmOptional<Int>()
@objc dynamic var pickupdate: String? = nil
enum CatCodingKeys: String, CodingKey {
case orderId
case userId
case pickupdate
}
convenience required init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CatCodingKeys.self)
self.orderId.value = try container.decodeIfPresent(Int.self, forKey: .orderId)
self.userId.value = try container.decodeIfPresent(Int.self, forKey: .userId)
self.pickupdate = try container.decodeIfPresent(String.self, forKey: .pickupdate)
}
required init() {
super.init()
}
required init(value: Any, schema: RLMSchema) {
super.init(value: value, schema: schema)
}
required init(realm: RLMRealm, schema: RLMObjectSchema) {
super.init(realm: realm, schema: schema)
}
}
将服务器端数据解码为领域兼容:
let decoder = JSONDecoder()
do {
let orders = try decoder.decode(Array<UserOrderHistory>.self, from: data)
try? realm!.write {
realm?.add(orders.orderlist!)
}
}catch {
print(error)
}
问题出在哪里。
- 我该如何解决这个问题。
- 有没有其他简单的方法来解析这种类型的 json 以使用可解码的。
上面提到了错误。
解决方案
OrderList 是一个array
. 您需要更改类中的orderList
变量UserOrderHistory
:
var orderlist: [OrderList]?
仅保留此行,删除Array
:
let orders = try decoder.decode([UserOrderHistory].self, from: data)
至 :
let orders = try decoder.decode(UserOrderHistory.self, from: data)
推荐阅读
- excel - 我需要有一个动态报告数据来自另一个工作表。什么是正确的公式?
- python - 无法使用 Python-Flask 在 html 中设置变量值 - 值转换为编码格式
- neo4j - 内置企业版程序不可用
- javascript - 无法让 Promise 依次评估
- javascript - 如何在背景图片中添加 id
- c# - 如何在身份服务器事件处理程序(IEventSink)中获取访问令牌
- python - 如何为具有不同类型和大小的 6 个参数的函数实现多处理
- javascript - ACF Gutenberg 块未在后端渲染光滑的滑块
- javascript - 在网页 HTML/Javascript 中的两个菜单选项卡之间切换
- vue.js - 在 Vue.js 中使用 $emit() 方法将数据从子级传递到父级到父级