JSON को Swift Codable struct में बदलें!

JSON डालें और nested object समेत Swift Codable struct कोड बनाएं! Codable, CodingKeys, JSONDecoder, iOS समर्थित।
JSON
परिणाम
 

JSON को Swift Codable struct में बदलें!

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 चाहिए हों।

उपयोग कैसे करें

  1. अपने API का response body पेस्ट करें, उदाहरण के लिए Proxyman या Charles से पकड़ा गया।
  2. टाइप का नाम में top-level struct का नाम सेट करें (उदाहरण के लिए EpisodePage)।
  3. परिणाम को Swift फ़ाइल में पेस्ट करें; import Foundation शामिल है।
  4. try JSONDecoder().decode(EpisodePage.self, from: data) से decode करें।

उदाहरण

इनपुट (JSON)
{
  "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
}
आउटपुट (Swift · Codable)
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 मिलता है।

समर्थित सुविधाएँ

  • हर struct Codable अपनाता है; properties immutable let हैं।
  • snake_case और kebab-case keys camelCase properties बनती हैं, और सिर्फ़ तब मूल keys के साथ enum CodingKeys: String, CodingKey जुड़ता है।
  • Types: String, Int, Double, Bool, और arrays के लिए [T]।
  • कुछ items में न मौजूद या null वाले fields Optionals (String?) होते हैं, इसलिए न मौजूद keys भी decode हो जाती हैं।
  • मिले-जुले type की values एक बनाया गया, decode होने लायक JSONValue enum इस्तेमाल करती हैं।
  • default, class या self जैसे Swift keywords backticks में लपेटे जाते हैं।
  • Top-level array typealias Root = [RootItem] बनाता है।

उपयोग के मामले

async/await के साथ URLSession

एक sample response से ऐसा model मिलता है जिसे आप let (data, _) = try await URLSession.shared.data(from: url) के ठीक अगली line में decode कर सकते हैं।

SwiftUI list screens

बने हुए struct में Identifiable जोड़ें (जब उसमें id field हो) और उसे सीधे List(page.episodes) { ... } में दें।

Bundle किया गया mock data

Design चरण का sample JSON app bundle में रखें और उसी model से decode करें, ताकि असली API तैयार होने से पहले screens बनाई जा सकें।

नोट्स और सीमाएँ

  • Swift मॉडल में तारीख वाली strings भी String ही रहती हैं। Date पाने के लिए property type बदलें और decoder.dateDecodingStrategy = .iso8601 जैसी strategy सेट करें।
  • अगर किसी non-optional property की key response में न हो, तो decoding DecodingError.keyNotFound देती है। जिन fields को API छोड़ सकता है उन पर ? जोड़ें, भले ही आपके sample में वे हमेशा रहे हों।
  • सभी properties 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 विफल होती है।

Classes नहीं, structs क्यों?

Response models को value types मानना Swift का आम convention है, और structs को memberwise initializer मुफ़्त में मिलता है, जिससे test data बनाना आसान होता है। Reference semantics चाहिए तो final class में बदलें और initializer जोड़ें।

जिस field को मैं integer समझ रहा था वह Double आया।

जब किसी key में integers और decimals दोनों हों, तो Double precision खोने से बचाता है। उल्टे, अगर हर sample वैल्यू 4.0 जैसी है, तो browser का JSON parser उसे integer पढ़ता है और आपको Int मिल सकता है, इसलिए असली API values जांचें।

क्या वापस JSON में encode करने पर मूल keys बनी रहती हैं?

CodingKeys encoding के लिए भी इस्तेमाल होते हैं, इसलिए JSONEncoder फिर से guest_name लिखता है। nil वाली Optional properties आउटपुट से छोड़ दी जाती हैं।