How to parse a JSON file in swift?

ios, swift

Solution

This answer was last revised for Swift 5.3 and iOS 14.4 SDK.

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)

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"
    },
    ...
]

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
}

Then decode the data with `JSONDecoder`:

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

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.

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

Problem

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.

Original source

Related problems