Search code examples
iosiphoneobjective-cjsonviewdidload

Accessing json structure to capture data in iOS.


I have the following code and it is working to an extent :

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    NSString *strURL = [NSString stringWithFormat:@"http://localhost:8888/service.php"];
    NSURL *url = [NSURL URLWithString:strURL];

    NSData * data = [NSData dataWithContentsOfURL:url];
    NSError * error;
    NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    AdObject *someAdObject = [[AdObject alloc] init];



    //NSLog(@"%@", json);
    self.detailLabel.text = self.tempString;

}

Now when the commented out NSLog actually prints the JSON dictionary, I get :

        {
        brand = "";
        category = Games;
        country = "Japan";
        "discount_rate" = 50;
        duration = 5;
        id = 1;
        "issue_date" = "2014-04-07";
        location = "Heishi Mall";
        title = "Gamestory videogames sales!";
        user = "";
    }
)

I created an Ad object which has properties such as title, location, country, etc (as reflected above). I would like to access the JSON above and store value in object variables.


Solution

  • You can access that values :-

     for(NSDictionary *item in json) {                  
        NSLog(@"%@",[item valueForKey:@"key"]);
       someAdObject.key  = [item valueForKey:@"key"];                 
     }