我有以下代码,它的工作范围很广:
- (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
并在对象变量中存储值。
答案 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
}