You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. 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
  1. Convert the string to NSData (required for JSON parsing):
NSData *socialJsonData = [socialJsonString dataUsingEncoding:NSUTF8StringEncoding];
  1. Parse the JSON data into an NSDictionary, with error handling:
NSError *parseError = nil;
NSDictionary *socialDict = [NSJSONSerialization JSONObjectWithData:socialJsonData
                                                           options:0
                                                             error:&parseError];
  1. 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"]) over objectForKey: for cleaner code, but both work.

内容的提问来源于stack exchange,提问作者Sani mori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:32:32