Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在iphone应用程序上解析JSON对象和子元素_Iphone_Ios_Arrays_Xcode_Json - Fatal编程技术网

在iphone应用程序上解析JSON对象和子元素

在iphone应用程序上解析JSON对象和子元素,iphone,ios,arrays,xcode,json,Iphone,Ios,Arrays,Xcode,Json,我正在构建一个使用UPC数据库API的应用程序。我得到了一个JSON对象,示例如下: 现在,我如何以数组形式从myArray中获取“成分”?您将以数组的形式获得结果,但(用JSON术语)它不是数组。大概是这样的:1 然后,您可以从中获取内部成分对象: NSString *ingredients = [result objectForKey:@"ingredients"]; 根据@bavariable'评论编辑 1由于我对Objective-C不太熟悉,因此针对明显错误提出了建议。您可能需要为

我正在构建一个使用UPC数据库API的应用程序。我得到了一个JSON对象,示例如下:


现在,我如何以数组形式从myArray中获取“成分”?

您将以数组的形式获得
结果,但(用JSON术语)它不是数组。大概是这样的:1

然后,您可以从中获取内部
成分
对象:

NSString *ingredients = [result objectForKey:@"ingredients"];
根据@bavariable'评论编辑



1由于我对Objective-C不太熟悉,因此针对明显错误提出了建议。您可能需要为返回的
NSDictionary
NSString
指针分配内存;我不确定。

以下是您需要做的所有事情:

 NSDictionary *json_dict = [theResponseString JSONValue];

 // Use a key path to access the nested element.
 NSArray *myArray = [json_dict valueForKeyPath:@"result.ingredients"];
编辑

哎呀,马特说得对。以下是如何处理字符串值:

 // Use a key path to access the nested element.
 NSString *s = [json_dict valueForKeyPath:@"result.ingredients"];
 NSArray *ingredients = [s componentsSeparatedByString:@", "];

请注意,您可能需要从数组的最后一个元素中删除“.”字符。

谢谢,但我需要数组形式的成分,以便访问每个成分。这很好。不幸的是,出于您的目的,您一直使用JSON中的格式。这意味着您首先必须以字符串形式检索成分,然后将
(逗号)上的字符串拆分为一个数组。我同意JSON格式是愚蠢的,但必须按你的意愿行事。或者,你知道,使用不同的API.RTFM,伙计。或者我建议使用
-objectForKey:
,规范的
NSDictionary
方法从字典中检索元素,而不是
-valueForKey:
。请参见@BAV,谢谢,相应编辑。就像我说的:我真的不知道Objective-C<代码>结果。成分
不是数组。这是一个字符串。很好的尝试-本来可以很好和干净,但在这种情况下myArray不是数组-它是一个字符串(而且,在它上运行“count”会使应用程序崩溃)。Matt是对的-它是一个字符串,所以看起来必须使用蛮力。
NSString *ingredients = [result objectForKey:@"ingredients"];
 NSDictionary *json_dict = [theResponseString JSONValue];

 // Use a key path to access the nested element.
 NSArray *myArray = [json_dict valueForKeyPath:@"result.ingredients"];
 // Use a key path to access the nested element.
 NSString *s = [json_dict valueForKeyPath:@"result.ingredients"];
 NSArray *ingredients = [s componentsSeparatedByString:@", "];