NSJSONSerialization不创建键值对

时间:2011-12-31 17:56:55

标签: iphone nsdictionary nsdata nsjsonserialization

我使用iOS 5新功能来解析JSON,我不知道为什么我没有获得任何键值对。 “aStr”(数据的字符串表示)在输出窗口上放置了正确的JSON,但我在“dicData”中没有得到任何内容,也没有错误。

非常感谢任何帮助。

这就是我正在使用的

NSError *error = nil;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL        URLWithString:@"http://www.macscandal.com/?json=get_post&post_id=436"]];

NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];

//NSLog(@"data = %@",aStr);
NSDictionary *dicData = [NSJSONSerialization
                           JSONObjectWithData:data
                           options:NSJSONReadingAllowFragments
                           error:&error];
//NSLog(@"error = %@",error);
NSString *title = [dicData objectForKey:@"title"];

1 个答案:

答案 0 :(得分:1)

您的JSON格式如下:

{
  "status": "ok",
  "post": {
    "id": 436,
    "type": "post",
    "slug": "foxconn-likely-to-get-assembly-contract-for-apple-tv-set",
    "url": "http:\/\/www.macscandal.com\/index.php\/2011\/12\/28\/foxconn-likely-to-get-assembly-contract-for-apple-tv-set\/",
    "status": "publish",
    "title": "Foxconn Likely to get Assembly Contract for Apple TV Set",
...

我没有使用NSJSONSerialization但只是遵循自然的JSON解析alg,这就是我试图获得它的方式。

NSDictionary *dicData = [NSJSONSerialization
                           JSONObjectWithData:data
                           options:NSJSONReadingAllowFragments
                           error:&error];

NSDictionary *postData = [dicData objectForKey:@"post"];
NSString *title = [postData objectForKey:@"title"];

修改

只是一个简单的检查方法:

-(void)check{

    NSError *error = nil;
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.macscandal.com/?json=get_post&post_id=436"]];

    NSDictionary *dicData = [NSJSONSerialization
                             JSONObjectWithData:data
                             options:NSJSONReadingAllowFragments
                             error:&error];

    NSDictionary *postData = [dicData objectForKey:@"post"];
    NSString *title = [postData objectForKey:@"title"];

    NSLog(@"%@", title);
}