JSON Parse


Ö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;

[
{
"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",
}
}
]
view raw book.json hosted with ❤ by GitHub

JSON yapısı için init oluşturmadan Codable protokolünden inherit edebiliriz.

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)")
}
view raw codable.swift hosted with ❤ by GitHub

Hiç yorum yok:

Yorum Gönder

Yorumunuz için teşekkür ederim.