这是我的 JSON:
这是我创建的模型,但解码失败:
struct Response: Decodable {
let results: [Order]
}
struct Order: Decodable {
let charge_id: String
let createdAt: String
let items_bought : [BoughtItems]
let objectId: String
let soldBy: String
let total: String
let status: String
}
struct BoughtItems: Decodable {
let price: Int
let productTitle: String
let quantity: Int
let variantId: Int
let variantTitle: String
}
最佳答案
请捕获错误并处理它。 Codable
错误非常具有描述性。
Type 'Int' mismatch: Expected to decode Int but found a string/data instead.
codingPath: [CodingKeys(stringValue: "results", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "items_bought", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "price", intValue: nil)]
明确表示 BoughtItems
中的 price
是 String
而不是 Int
。
将 let price: Int
替换为 let price: String
后,你会得到另一个错误
Type 'String' mismatch: Expected to decode String but found a number instead.
codingPath: [CodingKeys(stringValue: "results", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "total", intValue: nil)]
这也很清楚了。 total
的类型是Double
,不是String
修复:让总计:双倍
请学习阅读 JSON。非常简单:
- 双引号中的所有内容(无异常(exception))都是
String
- float 值是
Double
- 其他数值是
Int
。 true
或false
(无双引号)是Bool
关于json - 我该如何在这个 JSON 之后创建一个 Struct 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50833557/