繁体   English   中英

如何在此JSON之后创建Struct模型?

[英]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错误非常具有描述性。

类型'Int'不匹配:预期解码Int,但找到了一个字符串/数据。

codingPath:[CodingKeys(stringValue:“ results”,intValue:nil),_JSONKey(stringValue:“ Index 0”,intValue:0),CodingKeys(stringValue:“ items_bought”,intValue:nil),_JSONKey(stringValue:“ Index0” “,intValue:0),CodingKeys(stringValue:“ price”,intValue:nil)]

明确指出BoughtItems中的priceString而不是Int

更换后let price: Intlet price: String ,你会得到另一个错误

类型“字符串”不匹配:预期会解码字符串,但找到了一个数字。

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
  • Booltrue还是false (没有双引号)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM