iOS开发求助:从嵌套JSON提取WhatsApp号码时程序崩溃
Fix for Crash When Accessing WhatsApp/Call Values from JSON String
Hey there! Let's break down why your app is crashing and how to fix it quickly.
The Root Cause
Right now, the social_dict variable you're getting from [shop_info valueForKey:@"extra_values"] isn't actually an NSDictionary—it's an NSString containing JSON-formatted text. Even though NSLog prints it like a dictionary, under the hood it's just a string. When you try to call objectForKey: (a method exclusive to NSDictionary) on a string, iOS throws an unrecognized selector exception, which crashes your app.
Step-by-Step Solution
You need to first parse that JSON string into a real NSDictionary before you can access its values. Here's how to do it properly:
- Get the raw JSON string (rename the variable to avoid confusion):
NSString *socialJsonString = [shop_info objectForKey:@"extra_values"]; // Note: Use objectForKey: instead of valueForKey: here if shop_info is an NSDictionary—KVC's valueForKey: can have unexpected behavior with dictionaries
- Convert the string to NSData (required for JSON parsing):
NSData *socialJsonData = [socialJsonString dataUsingEncoding:NSUTF8StringEncoding];
- Parse the JSON data into an NSDictionary, with error handling:
NSError *parseError = nil; NSDictionary *socialDict = [NSJSONSerialization JSONObjectWithData:socialJsonData options:0 error:&parseError];
- Safely access the values once parsing succeeds:
if (socialDict && !parseError) { NSString *whatsappNumber = socialDict[@"whatsapp"]; NSString *callNumber = socialDict[@"call"]; NSLog(@"WhatsApp Number: %@", whatsappNumber); NSLog(@"Call Number: %@", callNumber); } else { NSLog(@"Failed to parse JSON: %@", parseError.localizedDescription); }
Quick Notes
- Always add error handling when parsing JSON—this helps you debug cases where the JSON might be malformed.
- For dictionary access, prefer modern subscript syntax (
dict[@"key"]) overobjectForKey:for cleaner code, but both work.
内容的提问来源于stack exchange,提问作者Sani mori
相关产品推荐
相关产品推荐

