Önceki yazımda decodable ve encodable'dan bahsetmiştim. Şimdi codable ile JSON parse işlemini yapacağız.
JSON
JSON verilerimizi proje içine attığımız books.json dosyası içerisinden okuyacağız. Dosyanın içeriği;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"title": "XCode 9", | |
"link": "https://atakancengizkurt.com/swift/xcode-9-3234235235", | |
"person": { | |
"id": 1, | |
"firstName": "Atakan", | |
"lastName": "KURT", | |
} | |
}, | |
{ | |
"title": "XCode 10", | |
"link": "https://atakancengizkurt.com/swift/xcode-10-3234235235", | |
"person": { | |
"id": 1, | |
"firstName": "Atakan", | |
"lastName": "KURT", | |
} | |
} | |
] |
JSON yapısı için init oluşturmadan Codable protokolünden inherit edebiliriz.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Book: Codable{ | |
var title: String? | |
var link: String? | |
var person:Person? | |
} | |
struct Person: Codable{ | |
var id: Int? | |
var firstName: String? | |
var lastName: String? | |
} | |
//Yapıyı oluşturduğumuza göre birkaç satır ile Json Parse işlemimizi gerçekleştirebiliriz; | |
let path = Bundle.main.path(forResource: "books.json", ofType:"json") | |
guard let filePath = path, let jsonData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else {return} | |
do | |
{ | |
let books = try JSONDecoder().decode([Book].self, from: jsonData) | |
print(books.first?.person?.firstName) //Atakan | |
} | |
catch let error{ | |
print("Json Parse Erro: \(error)") | |
} |
Hiç yorum yok:
Yorum Gönder
Yorumunuz için teşekkür ederim.