从nsdictionary检索数据

时间:2013-08-22 15:24:46

标签: objective-c json nsdictionary

这是我的JSON文件:

 {"object":

     {"blog":[{"guid":181,"type":"object","subtype":"4","time_created":"1376731708","time_updated":"1376731708","container_guid":"180","owner_guid":"180","site_guid":"1","title":"ugg sito ufficiale italiavyt","description":"sdataa","url":"http:\urlt"}],

    "bookmarks":[
        {"guid":82,"type":"object","subtype":"9","time_created":"1372072736","time_updated":"1372072910","container_guid":"81","owner_guid":"33","site_guid":"1","title":"Eqtitler","description":"<description>","url":"http:\urler"},
        {"guid":75,"type":"object","subtype":"9","time_created":"1371728924","time_updated":"1371728924","container_guid":"64","owner_guid":"52","site_guid":"1","title":"Ttitleur","description":"<pdescriptionp>","url":"http:\urlr"}
    ]
},

"group":[
    [
        {"guid":83,"type":"group","subtype":"0","time_created":"1372073952","time_updated":"1372074727","container_guid":"33","owner_guid":"33","site_guid":"1","name":"titles","description":"description>","url":"http:\urls"},
        {"guid":81,"type":"group","subtype":"0","time_created":"1372067304","time_updated":"1372068113","container_guid":"33","owner_guid":"33","site_guid":"1","name":"titles","description":"<pdescriptionp>","url":"http:\/\urles"},
        {"guid":64,"type":"group","subtype":"0","time_created":"1371728148","time_updated":"1372068044","container_guid":"33","owner_guid":"33","site_guid":"1","name":"Gtitres","description":"<description>","url":"http:\/\urls"}
    ]
]
  }

我使用以下代码来解析我的json:

 NSError *error = nil;
 NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://s210678217.onlinehome.fr/?view=json"]];

 id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];

 NSDictionary *feed = [jsonObjects objectForKey:@"object"];
 NSArray *entries = [feed objectForKey:@"bookmarks"];

或者

NSArray *entries2 = [feed objectForKey:@"blog"];

此代码非常适合使用书签和博客检索数据。 只是,此代码无法检索组。 我不明白为什么?

2 个答案:

答案 0 :(得分:0)

{之前,您在json中缺少group。然后纠正它 试试这个:

NSArray *entries = [jsonObjects objectForKey:@"group"];

组是NSDictionary的数组。

答案 1 :(得分:0)

您可以简单地使用json-framework来解析任何json字符串。您应该在类中导入“SBJSON.h”,以下代码将您的JSON解析为NSArray。

NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://yourURL"]];
NSURLResponse *resp = nil;
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &error];
NSString *jsonString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //your json string from URL request
//JSON Parsing here
SBJsonParser* parser = [SBJsonParser new];
NSArray* myArr = [parser objectWithString:jsonString];    //parsed NSArray

您可以在此处下载此框架:(https://github.com/stig/json-framework/) 但是你应该有一个有效的JSON来解析它。