2

我正在使用 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"];
4

1 回答 1

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 解析算法,这就是我尝试获取它的方式。

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);
}
于 2011-12-31T18:44:35.697 回答