Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a JSON file in swift?

Tags:

ios

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.

like image 803
kmithi Avatar asked Jun 03 '14 10:06

kmithi


People also ask

How do I use JSON in Swift?

The first step to convert a JSON object to a Swift type is to create a model. For our example above, here's a struct we can use: As you can see, each JSON key will be represented by the property in the model above. Be sure to conform to the Codable protocol so it can be used to decode and encode JSON.

What is parse in Swift?

Parse is a platform that offers many tools and one of the things it provides is a “service as a back-end”. Parse takes care of the implementation of the back-end so that developers can focus on building their apps while still leveraging the power of having data persistence in the cloud.


1 Answers

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.

like image 113
akashivskyy Avatar answered Sep 29 '22 18:09

akashivskyy