json - 我该如何在这个 JSON 之后创建一个 Struct 模型?

标签 json swift codable

这是我的 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

修复:让总计:双倍


请学习阅读 JSON。非常简单:

  • 双引号中的所有内容(异常(exception))都是String
  • float 值是Double
  • 其他数值是Int
  • truefalse(无双引号)是 Bool

关于json - 我该如何在这个 JSON 之后创建一个 Struct 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50833557/

相关文章:

ios - 如何在 SignalR iOS 后台接收消息?

arrays - Swift:数组中元素出现的次数百分比?

ios - Swift 5 默认可解码实现,只有一个异常(exception)

swift - WrapperOfNSCoding 因单个值而失败

json - json的自动可视化

json - 如何选择一个值,这是可选的 - 使用 jq

javascript - 推送器未正确发布到服务器

javascript - 基于单击嵌套 ng-repeat 中的特定 json 数组来显示行?

ios - 容器比例 swift 4

ios - 如何处理与 Swift 4 Codable 不一致的 JSON 格式?