访问json结构以捕获iOS中的数据。

时间:2014-04-04 09:06:27

标签: ios iphone objective-c json viewdidload

我有以下代码,它的工作范围很广:

- (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;

}

现在当注释掉的NSLog实际打印出JSON字典时,我得到:

        {
        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 = "";
    }
)

我创建了一个广告对象,其中包含标题,位置,国家/地区等属性(如上所示)。我想访问上面的JSON并在对象变量中存储值。

2 个答案:

答案 0 :(得分:3)

您可以访问该值: -

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

答案 1 :(得分:1)

试试这个并查看您的json

AdObject *someAdObject = nil;
for(NSDictionary *item in json) {
    someAdObject = [[AdObject alloc] init];
    someAdObject.category = [item valueForKey@"category"]; 
    someAdObject.country = [item valueForKey@"country"]; 
    someAdObject.discount_rate = [item valueForKey@"discount_rate"]; 
    someAdObject.duration = [item valueForKey@"duration"]; 
    //and same all of your required object properties
}