← Back to Swift Course | Chapter 14: Standard Library & Best Practices | Lesson 3 of 7

Codable और JSON

Codable एक magic label है जो Swift को आपके custom types को JSON text में और वापस अपने आप translate करने देता है।
Syntax
swift
import Foundation

struct TypeName: Codable {
    var property: Type
}

let data = try JSONEncoder().encode(instance)
let decoded = try JSONDecoder().decode(TypeName.self, from: data)

Encoding a Struct to JSON

Codable conform करने वाला एक struct JSONEncoder उपयोग करके JSON Data में बदला जा सकता है, जिसे फिर आमतौर पर एक printable String में convert किया जाता है।

उदाहरण: Encoding a Struct to JSON

markup
// Import the `Foundation` module
import Foundation
// Define a struct `User`
struct User: Codable {
    var name: String
    var age: Int
}
// Declare a constant `user`, set to `User(name: "Nina", age: 29)`
let user = User(name: "Nina", age: 29)
// Declare a constant `data`, set to `try! JSONEncoder().encode(user)`
let data = try! JSONEncoder().encode(user)
// Print `String(data: data, encoding: .utf8)!` to the console
print(String(data: data, encoding: .utf8)!)

Decoding JSON Back into a Struct

JSONDecoder JSON Data को वापस एक Codable type में parse करता है, original structured value reconstruct करते हुए।

उदाहरण: Decoding JSON Back into a Struct

markup
// Import the `Foundation` module
import Foundation
// Define a struct `User`
struct User: Codable {
    var name: String
    var age: Int
}
// Declare a constant `json`, set to `"{\"name\":\"Leo\",\"age\":34}"`
let json = "{\"name\":\"Leo\",\"age\":34}"
// Declare a constant `data`, set to `json.data(using: .utf8)!`
let data = json.data(using: .utf8)!
// Declare a constant `decoded`, set to `try! JSONDecoder().decode(User.self, from: data)`
let decoded = try! JSONDecoder().decode(User.self, from: data)
// Print "\(decoded.name) is \(decoded.age)" to the console
print("\(decoded.name) is \(decoded.age)")
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. यह भूल जाना कि JSONEncoder/JSONDecoder इसे process करने से पहले एक type को Codable (या Encodable/Decodable) conform करना चाहिए।
  2. यह मान लेना कि JSON में property names हमेशा Swift property names से बिल्कुल match करते हैं; mismatches के लिए एक custom CodingKeys enum चाहिए।
  3. यह भूल जाना कि JSONEncoder().encode(_:) और JSONDecoder().decode(_:from:) दोनों throwing functions हैं जिन्हें try चाहिए।
चैप्टर सारांश
  • Codable (दोनों Encodable और Decodable) conform करने वाला एक type अपने आप JSON से/में convert हो सकता है।
  • JSONEncoder().encode(_:) एक Codable value को JSON वाले Data में बदलता है।
  • JSONDecoder().decode(_:from:) Data को वापस एक Swift type में parse करता है।
  • CodingKeys आपको यह customize करने देता है कि property names JSON keys से कैसे map होते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.