Swift4嵌套JSON解析:模型类的编码与解码实现问询
Complete Swift Codable Model for Your Nested JSON Response
Looks like you're halfway there with your RootClass! Let's finish the implementation and add the missing List struct to handle the nested JSON array. Here's the full, working code:
struct RootClass: Codable { let details: String? let itemCount: Int? let list: [List]? enum CodingKeys: String, CodingKey { case details = "Details" case itemCount = "ItemCount" case list = "List" } // Completed custom decoder init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) details = try values.decodeIfPresent(String.self, forKey: .details) itemCount = try values.decodeIfPresent(Int.self, forKey: .itemCount) list = try values.decodeIfPresent([List].self, forKey: .list) } // Optional custom encoder (for converting the model back to JSON) func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(details, forKey: .details) try container.encodeIfPresent(itemCount, forKey: .itemCount) try container.encodeIfPresent(list, forKey: .list) } }
Next, you need to define the List struct that represents each item in the List array from your JSON. I'll use a placeholder example—replace the properties with whatever matches your actual JSON structure:
struct List: Codable { let id: Int? let name: String? let description: String? // Adjust these keys to match your JSON's actual field names enum CodingKeys: String, CodingKey { case id = "Id" case name = "Name" case description = "Description" } // Optional custom decoder (remove if no special logic is needed) init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) id = try values.decodeIfPresent(Int.self, forKey: .id) name = try values.decodeIfPresent(String.self, forKey: .name) description = try values.decodeIfPresent(String.self, forKey: .description) } // Optional custom encoder (remove if no special logic is needed) func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encodeIfPresent(id, forKey: .id) try container.encodeIfPresent(name, forKey: .name) try container.encodeIfPresent(description, forKey: .description) } }
Key Tips to Keep in Mind:
- CodingKeys: These map your Swift property names to the actual keys in the JSON (case-sensitive!). If your JSON keys match your Swift property names exactly, you can skip the
CodingKeysenum entirely—Swift will auto-generate it for you. - Optional Properties: Using
?means the decoder won't throw an error if those keys are missing from the JSON. If a field is required, remove the?and usedecode()instead ofdecodeIfPresent(). - Auto-Synthesis: If you don't need custom logic for encoding/decoding, you can omit the
init(from:)andencode(to:)methods. Swift will generate them automatically, making your code much cleaner. For example, theRootClasscould be simplified to:struct RootClass: Codable { let details: String? let itemCount: Int? let list: [List]? enum CodingKeys: String, CodingKey { case details = "Details" case itemCount = "ItemCount" case list = "List" } }
Example Usage (Decoding JSON):
Here's how you'd use this model to decode a JSON response from an API or local file:
// Sample JSON data (replace with your actual data) let jsonString = """ { "Details": "Sample order details", "ItemCount": 2, "List": [ { "Id": 101, "Name": "Wireless Headphones", "Description": "Noise-cancelling over-ear model" }, { "Id": 102, "Name": "Portable Charger", "Description": "20000mAh fast-charging" } ] } """ if let jsonData = jsonString.data(using: .utf8) { do { let rootModel = try JSONDecoder().decode(RootClass.self, from: jsonData) print("Order Details: \(rootModel.details ?? "No details provided")") print("Total Items: \(rootModel.itemCount ?? 0)") rootModel.list?.forEach { item in print("- \(item.name ?? "Unnamed Item"): \(item.description ?? "No description")") } } catch { print("Decoding error: \(error.localizedDescription)") } }
内容的提问来源于stack exchange,提问作者stack qstns
相关产品推荐
相关产品推荐

