read a json file in swift

To read a JSON file in Swift, you can use the Codable protocol and the JSONDecoder class. Follow these steps:

  1. Define a struct that represents the structure of the JSON file you want to read. The struct must conform to the Codable protocol.
main.swift
struct Response: Codable {
    let name: String
    let age: Int
}
67 chars
5 lines
  1. Get the URL of the JSON file.
main.swift
guard let url = Bundle.main.url(forResource: "myfile", withExtension: "json") else { return }
94 chars
2 lines
  1. Read the JSON data from the file.
main.swift
let data = try Data(contentsOf: url)
37 chars
2 lines
  1. Decode the JSON data into an instance of the struct using a JSONDecoder object.
main.swift
let decoder = JSONDecoder()
let response = try decoder.decode(Response.self, from: data)
89 chars
3 lines

Here's the complete code:

main.swift
struct Response: Codable {
    let name: String
    let age: Int
}

guard let url = Bundle.main.url(forResource: "myfile", withExtension: "json") else { return }

do {
    let data = try Data(contentsOf: url)
    let decoder = JSONDecoder()
    let response = try decoder.decode(Response.self, from: data)
    print(response.name)
    print(response.age)
} catch {
    print(error.localizedDescription)
}
405 chars
17 lines

gistlibby LogSnag