ios - 解析嵌套的 JSON SWIFT 4

标签 ios json swift xcode codable

谁能告诉我我做错了什么?

这是我要解析的 JSON:

{
"results": {
    "AF": {
        "alpha3": "AFG",
        "currencyId": "AFN",
        "currencyName": "Afghan afghani",
        "currencySymbol": "؋",
        "id": "AF",
        "name": "Afghanistan"
    },
    "AI": {
        "alpha3": "AIA",
        "currencyId": "XCD",
        "currencyName": "East Caribbean dollar",
        "currencySymbol": "$",
        "id": "AI",
        "name": "Anguilla"
    }
}

我的代码:

class Results: Codable {
  let results: [Country]

  init(results: [Country]) {
    self.results = results
  }
}

class Country: Codable {

  let currencyId: String
  let currencyName: String
  let currencySymbol: String
  let id: String
  let name: String


  init(currencyId :String, currencyName: String, currencySymbol: String, id: String, name: String ) {

    self.currencyId = currencyId
    self.currencyName = currencyName
    self.currencySymbol = currencySymbol
    self.id = id
    self.name = name

  }
}

我看过 Apple 关于解码嵌套结构的文档,但我仍然不明白如何正确处理 JSON 的不同级别。

谢谢。

最佳答案

检查键 "results" 的概述值。

"results": {
    ...
}

{...} 表示 JSON 对象。在某些情况下,Swift struct(或 class 如果您认为更好)适合 JSON 对象。

在其他情况下,Swift Dictionary 可能更合适。

这个 JSON 对象的每个值都采用这种形式:

{
    "alpha3": ...,
    "currencyId": ...,
    "currencyName": ...,
    "currencySymbol": ...,
    "id": ...,
    "name": ...
}

与您的国家/地区匹配。

因此,您只需更改 Results 类中的 results 的类型即可。

class Results: Codable {
    let results: [String: Country]

    init(results: [String: Country]) {
        self.results = results
    }
}

属性及其类具有相同的名称(不区分大小写)可能会在将来引起一些混淆,但我现在保持原样。

你可以这样测试:

(假设在 Playground 中使用修改后的 Results 和您的 Country 进行测试。)

let jsonText = """
{
    "results": {
        "AF": {
            "alpha3": "AFG",
            "currencyId": "AFN",
            "currencyName": "Afghan afghani",
            "currencySymbol": "؋",
            "id": "AF",
            "name": "Afghanistan"
        },
        "AI": {
            "alpha3": "AIA",
            "currencyId": "XCD",
            "currencyName": "East Caribbean dollar",
            "currencySymbol": "$",
            "id": "AI",
            "name": "Anguilla"
        }
    }
}
"""
let jsonData = jsonText.data(using: .utf8)!

let decoder = JSONDecoder()
do {
    let results = try decoder.decode(Results.self, from: jsonData)
    print(results) //-> __lldb_expr_1.Results
} catch {
    print(error)
}

关于ios - 解析嵌套的 JSON SWIFT 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49847292/

相关文章:

ios - ABBYY Cloud OCR SDK 返回空的 authToken 作为响应?

ios - 设置 subview 比在 viewDidLoad 中更快

javascript - 为什么 parseJSON 在服务器的以下响应中失败?

json - Swift 从 AnyObject 创建 JSON 数据

ios - 当表格滚动时,重新加载行会使表格变为 "jump"

ios - HealthKit 计步器

ios - 如何将路径添加到将删除像素的 UIImage?

c# - 将复杂的 JSON 提交给 MVC Controller 。如何命名嵌套对象?

json - 如何从此json字段获取数据?

ios - UIView 子类设置自己的高度 + UIViewController 中的约束 + Swift 中的 Storyboard