小编K30*_*307的帖子

如何使用 Swift 结构正确解码嵌套的 JSON 对象

意图:

通过Coinmarketcap API接收加密货币价格数据,将其解码为 SWIFT 中的自定义结构,并可能将该数据存储在数据库(CoreData 或 SQLite)中。

语境:

我收到以下错误JSONDecoder().decode

Error serializing json: typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "status", intValue: nil), _DictionaryCodingKey(stringValue: "credit_count", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
Run Code Online (Sandbox Code Playgroud)

问题:

  1. 如何正确解释该错误?我解码错了什么?
  2. 我收到的数据格式是否正确?看起来不像是正确的 JSON。

编码:

import UIKit
import PlaygroundSupport


// Defining structures

struct RootObject: Decodable {
    let status: [String: StatusObject?]
    let data: DataObject?
}

struct StatusObject: Decodable {
    let credit_count: Int?
    let elapsed: Int?
    let error_code: Int?
    let timestamp: String? …
Run Code Online (Sandbox Code Playgroud)

json swift swift-dictionary swift-structs

5
推荐指数
1
解决办法
757
查看次数

标签 统计

json ×1

swift ×1

swift-dictionary ×1

swift-structs ×1