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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With