How to read a JSON File Using Swift

JSON stands for JavaScript Object Notation which is a standard text-based format for representing structured data based on JavaScript object syntax, we can use that in Swift, If you don’t have the JSON file you can create one Xcode->New->File->Strings
later you can rename .strings to .json & make sure it contains pure JSON only without any comments or markup.

#demoJSONFile look like below

{  
"country": "India"
}

1. To load JSON file from Bundle, use Bundle.main.url(forResource
2. To convert into decode object use JSONDecoder
3. The Json is converted into swift model using CodableModel

struct CodableModel: Decodable {
    var country: String
}
if let url = Bundle.main.url(forResource: "demoJSONFile", withExtension: "json") {
    do {
        let data = try Data(contentsOf: url)
        let decoder = JSONDecoder()
        let jsonModel = try decoder.decode(CodableModel.self, from: data)
        print(jsonModel.country)
      } catch {
           // Block for error handling
      }
}

The Source code is here .. That’s All 😊

Leave a Comment

Your email address will not be published. Required fields are marked *