2

I am using iOS 5 new feature to parse JSON and I have no idea that why I am not getting any key value pairs. "aStr" (string representation of data) is putting the right JSON on the output window but I am getting nothing in "dicData" and there is no error either.

Any help is greatly appreciated.

This is what I am using

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 に答える