-2

我是iOS的新手。我在访问我在 Web 应用程序服务器中检索到的 JSON 文件时遇到问题。

JSON:

{
"content": [
{
"info": [
  {
   "type": "TEL",
   "label": "Call Phone",
   "id": "32d7da39-39cc-4319-ab76-e67db9385722"
  }
],
   "name": "myname",
   "title": "myname_title",
   "image": "",
}
],
   "timestamp": 1370491676,
   "error": "SUCCESS"
}

我将 NSData 转换为 JSON :

NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];

当我使用此代码检索名称时:

NSString *name = [[mydatas objectForKey:@"content"] objectForKey:@"name"];

它终止程序。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x71e3240'
4

7 回答 7

1

从这里包含 SBJSon 框架

NSString *responseString = [[NSString alloc]initWithData: urlData encoding:NSUTF8StringEncoding];
    //NSLog(@"%@",responseString);
    NSDictionary * mydatas = [responseString JSONValue];
    NSString *name = [[mydatas objectForKey:@"content"]objectForKey:@"name"];
于 2013-06-06T04:32:33.840 回答
0

By looking at your JSON I can say,

Your mydatas dictionary contains 3 keys which are content, timestamp, error

The object for key content is an array. If you want to retrieve the object for key name you need to do the following

if([[mydatas objectForKey:@"content"] count]>0)
{
     NSString *name = [[[mydatas objectForKey:@"content"] objectAtIndex:0]objectForKey:@"name"]; 
}

This will work.

于 2013-06-06T04:35:43.440 回答
0

内容是一个NSArray,而不是一个NSDictionary。您需要使用NSArray调用来检索以下项目array

// Be sure to check that the array has at least one item or you'll throw an exception
NSArray *contentArray = [mydatas objectForKey:@"content"];
if ( contentArray.count > 0 ) {
   NSString *image = [contentArray[0] objectForKey:@"name"];
}
于 2013-06-06T04:16:16.780 回答
0

为什么您不使用 SBJSON 框架。https://github.com/stig/json-framework/

然后参考以下 SO 问题:如何将 JSON 解析为 Objective C-SBJSON。这将很容易让您解析这些数据。

于 2013-06-06T04:19:44.343 回答
0
NSArray *contentArray = [mydatas objectForKey:@"content"];

[contentArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
   NSLog(@"name of content at index %i is == %@",idx,[obj valueForKey:@"name"]);
}];
于 2013-06-06T04:23:35.427 回答
0

试试这样

NSString *name = [[[mydatas objectForKey:@"content"] objectAtIndex:0]objectForKey:@"name"];
于 2013-06-06T04:29:46.517 回答
0

试试这个

NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];  

将其保存到数组

NSArray *array = [mydatas objectForKey:@"content"];

for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:@"info"] forKey:@"info"];
[someArray addObject:dic];

[typeArray addObject:[[dic valueForKey:@"info"] valueForKey:@"type"] valueForKey:@"name"]];
NSString * NameStr = [typeArray objectAtIndex:i];
NSLog(@"String For Name : %@",NameStr);
[dic release];
}

希望它的工作!!!!!!!!!!!!

于 2013-06-06T05:35:12.173 回答