如何在iOS中访问my JSON



我是iOS新手。我有一个问题访问我的JSON文件,我检索在我的web应用程序服务器。

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'

从这里包含SBJSon框架

NSString *responseString = [[NSString alloc]initWithData: urlData encoding:NSUTF8StringEncoding];
    //NSLog(@"%@",responseString);
    NSDictionary * mydatas = [responseString JSONValue];
    NSString *name = [[mydatas objectForKey:@"content"]objectForKey:@"name"];

内容是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"];
}

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

请参考以下SO问题:如何将JSON解析为Objective C - SBJSON。

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"]);
}];

通过JSON,我可以说,

您的mydatas字典包含三个键:内容,时间戳,错误

键内容的对象是一个数组。如果要检索对象的键名,则需要执行以下操作

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

尝试一下,

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

试试这个

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];
}

Hope its Work!!!!!!!!!!!

最新更新