在 JSON 之后,我该如何着手创建结构模型?

How Do I go about creating a Struct model after this JSON?

这是我的 JSON:

https://pastebin.com/8HR6jcuC

这是我创建的模型,但解码失败:

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 中的 priceString 而不是 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

修复:let total: Double


请学习阅读JSON。很简单:

  • 双引号中的所有内容(例外)是String
  • 浮点数值是 Double
  • 其他数值为Int
  • truefalse(无双引号)是 Bool