JSON को Codable अपनाने वाले Swift structs में बदलें। Properties let से declare होती हैं और camelCase में rename होती हैं, और CodingKeys enum सिर्फ़ उन structs के लिए बनता है जहां कोई नाम अपनी JSON key से अलग हो।
इसे तब इस्तेमाल करें जब iOS या macOS app को URLSession response को JSONDecoder से decode करने के लिए model चाहिए, या जब SwiftUI preview के पीछे के mock JSON से मेल खाते types चाहिए हों।
टाइप का नाम में top-level struct का नाम सेट करें (उदाहरण के लिए EpisodePage)।import Foundation शामिल है।try JSONDecoder().decode(EpisodePage.self, from: data) से decode करें।{
"podcast": "Swift Talk",
"episodes": [
{ "id": 301, "title": "Async Sequences", "duration": 1840, "explicit": false },
{ "id": 302, "title": "Macros", "duration": 2215.5, "explicit": false, "guest_name": "Chris" }
],
"total_count": 2
}import Foundation
struct EpisodePage: Codable {
let podcast: String
let episodes: [Episode]
let totalCount: Int
enum CodingKeys: String, CodingKey {
case podcast
case episodes
case totalCount = "total_count"
}
}
struct Episode: Codable {
let id: Int
let title: String
let duration: Double
let explicit: Bool
let guestName: String?
enum CodingKeys: String, CodingKey {
case id
case title
case duration
case explicit
case guestName = "guest_name"
}
}
episodes array के elements Episode struct बनते हैं। duration में integer (1840) और decimal (2215.5) दोनों हैं, इसलिए वह Double है; सिर्फ़ दूसरे episode में मिला guest_name guestName: String? है। Rename हुए field वाले हर struct को अपनी सभी keys सूचीबद्ध करने वाला CodingKeys enum मिलता है।
Codable अपनाता है; properties immutable let हैं।enum CodingKeys: String, CodingKey जुड़ता है।String, Int, Double, Bool, और arrays के लिए [T]।null वाले fields Optionals (String?) होते हैं, इसलिए न मौजूद keys भी decode हो जाती हैं।JSONValue enum इस्तेमाल करती हैं।default, class या self जैसे Swift keywords backticks में लपेटे जाते हैं।typealias Root = [RootItem] बनाता है।एक sample response से ऐसा model मिलता है जिसे आप let (data, _) = try await URLSession.shared.data(from: url) के ठीक अगली line में decode कर सकते हैं।
बने हुए struct में Identifiable जोड़ें (जब उसमें id field हो) और उसे सीधे List(page.episodes) { ... } में दें।
Design चरण का sample JSON app bundle में रखें और उसी model से decode करें, ताकि असली API तैयार होने से पहले screens बनाई जा सकें।
String ही रहती हैं। Date पाने के लिए property type बदलें और decoder.dateDecodingStrategy = .iso8601 जैसी strategy सेट करें।DecodingError.keyNotFound देती है। जिन fields को API छोड़ सकता है उन पर ? जोड़ें, भले ही आपके sample में वे हमेशा रहे हों।let हैं; जिन models को view state के रूप में बदलते हैं उनके लिए var पर जाएं।Identifiable या Hashable जैसे अतिरिक्त protocols नहीं अपनाए जाते।JSONValue enum मिले-जुले types के लिए helper कोड है; अगर आपके project में पहले से ऐसा type है, तो इसे हटाकर अपना इस्तेमाल करें।keyDecodingStrategy = .convertFromSnakeCase के साथ क्या CodingKeys हटा सकते हैं?हां, तब decoder guest_name ↔ guestName खुद बदल देता है। लेकिन दोनों को एक साथ न मिलाएं: decoder पहले keys को camelCase में बदलता है और फिर उन्हें CodingKeys के "guest_name" raw value से compare करता है, इसलिए matching विफल होती है।
Response models को value types मानना Swift का आम convention है, और structs को memberwise initializer मुफ़्त में मिलता है, जिससे test data बनाना आसान होता है। Reference semantics चाहिए तो final class में बदलें और initializer जोड़ें।
Double आया।जब किसी key में integers और decimals दोनों हों, तो Double precision खोने से बचाता है। उल्टे, अगर हर sample वैल्यू 4.0 जैसी है, तो browser का JSON parser उसे integer पढ़ता है और आपको Int मिल सकता है, इसलिए असली API values जांचें।
CodingKeys encoding के लिए भी इस्तेमाल होते हैं, इसलिए JSONEncoder फिर से guest_name लिखता है। nil वाली Optional properties आउटपुट से छोड़ दी जाती हैं।