Tuesday, 18 June 2013

Read JSON from NSBundle file iOS.


-(void)fetchJSONDict
{
//  Goto the filePath

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"JsonFile" ofType:@"txt"];
    NSString *jsonContent = [NSString stringWithContentsOfFile:filePath usedEncoding:nil error:nil];
    NSLog(@"content Json is:%@",jsonContent);

    NSData *data = [jsonContent dataUsingEncoding:NSUTF8StringEncoding];
    id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; //Check out other options NSJSONReadingOptions available. 


//  Check the class type of the object fetched.


    if([object isKindOfClass:[NSDictionary class]]) {
        _dataRXDict = [[NSDictionary alloc]initWithDictionary:object];
        NSLog(@"Json Object recieved is dictionary");
        NSLog(@"Json Object Test:%@",[object valueForKey:@"myKey"]);
    }
    else if([object isKindOfClass:[NSArray class]]) {
        _dataRXArray = [[NSArray alloc]initWithArray:object];

        NSLog(@"Json Object recieved is array");
        NSLog(@"Json Object Test:%@",[object objectAtIndex:0]);
    }
    else if([object isKindOfClass:[NSString class]]) {
        _dataRXString = [[NSDictionary alloc]initWithDictionary:object];

        NSLog(@"Json Object recieved is string");
        NSLog(@"Json Object Test:%@",object);
    }
}


No comments:

Post a Comment