To parse a JSON file in Swift, we can use the Codable protocol provided by Swift standard library's Foundation framework. Here's an example:
Assuming we have a JSON file data.json
that contains the following data:
73 chars6 lines
We can define a struct that conforms to the Codable protocol, with properties matching the keys in the JSON data:
main.swift87 chars6 lines
To parse the JSON file into an instance of our Person
struct, we can use a JSONDecoder
and read the contents of the file into a Data
object:
main.swift195 chars5 lines
In the above example, we first create a JSONDecoder
instance, then retrieve the URL of our data.json
file using the Bundle
API. We then read the contents of that file into a Data
object using the contentsOf
method of the Data
class. Finally, we decode the JSON data using the decode
method of the JSONDecoder
class and our Person
struct as the generic parameter.
We can now access the properties of the parsed person
object:
main.swift103 chars4 lines
gistlibby LogSnag