使用JSON Decoder解析Instagram用户JSON失败问题求助
Hey there, let's work through this JSON decoding problem together. Based on the partial model you shared, here are the most common issues and actionable fixes to get your JSONDecoder working correctly:
1. Fix Truncated & Mismatched Field Names
First off, your mutual_followers_coun... field is cut off—this is almost certainly causing a decoding failure. Double-check the exact key name from Instagram's JSON response (it’s likely mutual_followers_count) and update your model to match perfectly.
Also, if Instagram uses snake_case (like clear_client_cache) but your Swift model uses camelCase, enable the built-in snake_case decoding strategy to avoid manual key mapping:
let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase
2. Verify Type Compatibility
Instagram’s API sometimes returns boolean values as integers (1/0) instead of true/false, or string values for numeric fields in edge cases. For example:
- If the JSON returns
"1"(a string) instead of1(an integer) forclear_client_cache, yourInttype will throw an error. - If
is_verifiedis a boolean in the JSON but your model usesInt, that’ll also fail.
To fix type mismatches, you can either adjust your model’s types or implement custom decoding. Here’s how to handle integer-based booleans:
struct InstaUser: Decodable { var byline: String? var followerCount: Int? var fullName: String? var hasAnonymousProfilePicture: Bool var isVerified: Bool var mutualFollowersCount: Int? enum CodingKeys: String, CodingKey { case byline, followerCount = "follower_count", fullName = "full_name" case hasAnonymousProfilePicture = "has_anonymous_profile_picture" case isVerified = "is_verified", mutualFollowersCount = "mutual_followers_count" } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) byline = try container.decodeIfPresent(String.self, forKey: .byline) followerCount = try container.decodeIfPresent(Int.self, forKey: .followerCount) fullName = try container.decodeIfPresent(String.self, forKey: .fullName) // Convert 1/0 integers to Bool let hasAnonymousInt = try container.decode(Int.self, forKey: .hasAnonymousProfilePicture) hasAnonymousProfilePicture = hasAnonymousInt == 1 let isVerifiedInt = try container.decode(Int.self, forKey: .isVerified) isVerified = isVerifiedInt == 1 mutualFollowersCount = try container.decodeIfPresent(Int.self, forKey: .mutualFollowersCount) } }
3. Ignore Unknown Keys
Instagram’s API might return extra fields not defined in your model. By default, JSONDecoder throws an error when it encounters unknown keys. To ignore them (available in iOS 13+/macOS 10.15+), add this:
decoder.unknownKeysStrategy = .ignore
4. Capture & Analyze Exact Decoding Errors
The fastest way to pinpoint the issue is to catch the decoding error and print detailed context. Replace your decoding code with this:
do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase decoder.unknownKeysStrategy = .ignore let userData = try decoder.decode(User.self, from: yourJsonData) print("Success! Decoded user data: \(userData)") } catch { print("Decoding failed with error: \(error)") // Get granular details to fix the root cause if let decodingError = error as? DecodingError { switch decodingError { case .keyNotFound(let key, let context): print("Missing key: \(key.stringValue) - \(context.debugDescription)") case .typeMismatch(_, let context): print("Type mismatch: \(context.debugDescription)") case .valueNotFound(_, let context): print("Value missing: \(context.debugDescription)") case .dataCorrupted(let context): print("Data corrupted: \(context.debugDescription)") @unknown default: print("Unknown decoding error") } } }
This will tell you exactly which key is missing, which type doesn’t match, or where the data is corrupted—making it trivial to fix your model.
Final Quick Checks
- Ensure optional fields (
?) are only used for fields that might actually be missing from the JSON. - Double-check nested models: your
Usersstruct has auser: InstaUser?—if the JSON always includes auserobject, remove the optional (?) to avoid unexpected nil values.
内容的提问来源于stack exchange,提问作者Max Kraev

