【问题标题】:How can I make a struct to decode JSON structure in Swift?如何制作一个结构来解码 Swift 中的 JSON 结构?
【发布时间】:2020-11-28 22:35:15
【问题描述】:

如何制作一个结构或类来快速解码以下类型的 json 结构?我想主要提取报表节点数据!

{
    "earliest": "2020-10-17",
    "latest": "2020-10-28",
    "report": {
        "purchase": {
            "total": 1458600.0,
            "average": 121550.0,
            "min": 600000.0,
            "max": 1600.0
        },
        "sale": {
            "total": 434250.0,
            "average": 144750.0,
            "min": 360000.0,
            "max": 29250.0
        },
        "production": {
            "total": 792030,
            "average": 20308.46153846154,
            "min": 12000,
            "max": 29700
        }
    }
}

【问题讨论】:

  • youtube上有很多这方面的教程,如果你google“Encode Decode JSON in swift”,你应该很容易找到答案

标签: json swift codable decodable encodable


【解决方案1】:

您只需要构建您的数据并使其符合 Codable:

struct Root: Codable {
    let earliest: String
    let latest: String
    let report: Report
}

struct Report: Codable {
    let purchase: Results
    let sale: Results
    let production: Results
}

struct Results: Codable {
    let total: Int
    let average: Double
    let min: Int
    let max: Int
}

let json = """
{
    "earliest": "2020-10-17",
    "latest": "2020-10-28",
    "report": {
        "purchase": {
            "total": 1458600.0,
            "average": 121550.0,
            "min": 600000.0,
            "max": 1600.0
        },
        "sale": {
            "total": 434250.0,
            "average": 144750.0,
            "min": 360000.0,
            "max": 29250.0
        },
        "production": {
            "total": 792030,
            "average": 20308.46153846154,
            "min": 12000,
            "max": 29700
        }
    }
}
"""

do {
    let report = try JSONDecoder().decode(Root.self, from: .init(json.utf8)).report
    print("report", report)
} catch {
   print(error)
}

报告报告(购买:结果(总计:1458600,平均:121550.0,最小:600000,最大:1600),销售:结果(总计:434250,平均:144750.0,最小:360000,最大:29250),生产:结果(总数:792030,平均:20308.46153846154,最小:12000,最大:29700))

【讨论】:

  • 您好,感谢您的回答。实际上,我一直在做同样的事情,直到我意识到它没有被解析,因为在“购买”和“销售”节点内,“总计”、“最小”、“最大”的值在“双”中,而在“生产”中' 节点位于“Int”中。看起来超级愚蠢,但不幸的是,这就是 swift 的工作方式(smh)。再次感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2020-11-29
  • 2016-11-28
  • 2020-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多