如何快速解析 JSON 文件? [英] How to parse a JSON file in swift?

查看:29
本文介绍了如何快速解析 JSON 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JSON 文件,想在表视图中解析和使用对象列表.任何人都可以分享快速解析JSON文件的代码吗?

I have a JSON file, want to parse and use list of objects in table view. Can any one share the code to parse JSON file in swift.

推荐答案

此答案最后修订为 Swift 5.3 和 iOS 14.4 SDK.

给定一些已经获得的 JSON 数据,您可以使用 JSONDecoder 将其解码为您的 Decodable 模型(或模型集合).

Given some already obtained JSON data, you can use JSONDecoder to decode it into your Decodable model (or a collection of models).

let data: Data = /* obtain your JSON data */
let model = try JSONDecoder().decode(Model.self, from: data)

此类模型必须符合 Decodable 协议并包含属性和 JSON 字典键之间的正确映射.例如,考虑以下包含以Wa"开头的城市搜索结果的 JSON 数组.

Such model must conform to the Decodable protocol and contain correct mapping between properties and JSON dictionary keys. As an example, consider the following JSON array containing search results of cities beginning with "Wa".

[
    {
        "id": 123,
        "city": "Washington",
        "region": "D.C.",
        "country": "United States"
    },
    {
        "id": 456,
        "city": "Warsaw",
        "region": "Mazowieckie",
        "country": "Poland"
    },
    ...
]

为此,您需要创建一个包含正确类型的正确属性的模型.如果您使用的是 Web API,那么它的文档将在此处提供很大帮助.

For that, you need to create a model that contains the correct properties of correct types. If you're using a web API, its documentation will be of great help here.

struct SearchResult: Decodable {
    let id: Int
    let city: String
    let region: String
    let country: String
}

然后用JSONDecoder解码数据:

let results = try JSONDecoder().decode([SearchResult].self, from: data)

给定一个新的解码搜索结果数组,调用 UITableView 的函数之一来重新加载其数据.请注意,decode 函数可能会抛出一个您必须以某种方式处理的错误.

Given a new array of decoded search results, call one of UITableView's functions to reload its data. Note that the decode function can throw an error which you must somehow handle.

要了解有关在 Swift 中解码自定义类型以及 Codable API 的更高级用法的更多信息,我建议查看 这篇文档文章.

To learn more about decoding custom types in Swift and more advanced usage of the Codable APIs, I recommend checking out this documentation article.

这篇关于如何快速解析 JSON 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆