Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
57 views
in Technique[技术] by (71.8m points)

ios - How to parse a JSON file in swift?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...