学习MVVM模式时JSON映射对象返回nil问题求助
Hey there! Let's figure out why your SearchResultObj properties are coming up nil after JSON mapping. From what you shared, there are a couple of key issues to fix—let's dive in:
1. Your Initializer Isn't Built for JSON Mapping
Looking at your code snippet, the init(model: SearchResultObj) is designed to copy an existing instance of your class, not convert raw JSON into a new object. That's probably why your properties aren't getting populated from the JSON response.
You need an initializer that takes the raw JSON data (usually a [String: Any] dictionary) and maps each key to your object's properties.
Fix: Add a Dictionary-Based Initializer
Here's how to rewrite your class with an initializer that handles JSON dictionaries properly:
class SearchResultObj: NSObject { var status: Bool var name: String? var publicKey: String? var profileImage: String? var accountType: String? // Initializer for JSON mapping init?(json: [String: Any]) { // First, safely extract required properties like `status` guard let statusValue = json["status"] as? Bool else { // Return nil if required property is missing return nil } self.status = statusValue // Map optional properties from JSON self.name = json["name"] as? String self.publicKey = json["publicKey"] as? String self.profileImage = json["profileImage"] as? String self.accountType = json["accountType"] as? String super.init() } // Optional: Keep your copy initializer if you still need it init(model: SearchResultObj) { self.status = model.status self.name = model.name self.publicKey = model.publicKey self.profileImage = model.profileImage self.accountType = model.accountType super.init() } }
2. Double-Check JSON Key Matching
Make sure the keys in your JSON response exactly match the property names in SearchResultObj (Swift is case-sensitive!). For example, if your JSON uses profile_image instead of profileImage, you'll need to adjust the mapping logic or use key decoding strategies if you switch to Codable.
3. Use Codable for Cleaner, Less Error-Prone Mapping
Since you're working in Swift, the Codable protocol is a far more maintainable way to handle JSON mapping. It eliminates manual dictionary parsing and reduces human error. Here's how to refactor your class to use Codable:
class SearchResultObj: NSObject, Codable { var status: Bool var name: String? var publicKey: String? var profileImage: String? var accountType: String? // If JSON uses snake_case instead of camelCase, add this enum to map keys enum CodingKeys: String, CodingKey { case status case name case publicKey = "public_key" case profileImage = "profile_image" case accountType = "account_type" } } // How to decode JSON data into your object: if let jsonData = yourJSONResponse.data(using: .utf8) { do { let searchResult = try JSONDecoder().decode(SearchResultObj.self, from: jsonData) // Your populated object is ready to use here! } catch { print("Decoding error: \(error)") // This will tell you exactly what went wrong } }
4. Quick Debugging Tips
- Print the raw JSON response to confirm it contains all the keys you're expecting.
- Add print statements in your initializer to check if each JSON value is being extracted correctly.
- If using Codable, always catch decoding errors—they'll point you directly to missing or mismatched keys.
Let me know if you need help adapting any of this to your specific JSON structure!
内容的提问来源于stack exchange,提问作者Erent

